Search code examples
javafilesymfonyweb-servicescodenameone

How to POST File to an URL in Java CodeName One?


I want to upload an image in java and copied in a directory with WebService in Symfony.

I tried it with Postman and it worked but when i did it in Java, it didn't work, I don't know how to pass a file like parameter in the Url request.

Please help me to find a solution

Symfony code:

    $file = $request->files->get('nomImage');
    $status = array('status' => "success","fileUploaded" => false);

    // If a file was uploaded
    if(!is_null($file)){
        // generate a random name for the file but keep the extension
        $filename = uniqid().".".$file->getClientOriginalExtension();
        $path = "C:\wamp64\www\pidev\web\uploads\images";
        $file->move($path,$filename); // move the file to a path
        $status = array('status' => "success","fileUploaded" => true);
    }

    return new JsonResponse($status);

Postman screenshot: I sent the URL with Postman and add the image in body with nomImage like key and the image like value and it worked

enter image description here

Java Code: This code is to connect to the URL and i wanted to get the image like file in the URL like in Postman

    public void ajoutProduit(File image)
    {
    ConnectionRequest con = new ConnectionRequest();
    con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
    NetworkManager.getInstance().addToQueueAndWait(con);
    }

This is my form and the uploading of the image and execute the Copy of the image which it didn't work

public class AjoutProduit {


private Form fAjout = new Form("", new BoxLayout(BoxLayout.Y_AXIS));
public AjoutProduit() {    
    
    TextField nomProduit = new TextField("", "Nom du produit");
    TextField descProduit = new TextField("", "Description du produit");
    ComboBox<String> opProduit = new ComboBox<>(
            "",
            "echanger",
            "donner",
            "recycler",
            "reparer"
    );

    final String[] jobPic = new String[1];
    Label jobIcon = new Label();

    Button image = new Button("Ajouter une image ");
    final String[] image_name = {""};
    final String[] pathToBeStored={""};

    /////////////////////Upload Image
    image.addActionListener((ActionEvent actionEvent) -> {
    Display.getInstance().openGallery(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ev) {
            if (ev != null && ev.getSource() != null) {
                String filePath = (String) ev.getSource();
                int fileNameIndex = filePath.lastIndexOf("/") + 1;
                String fileName = filePath.substring(fileNameIndex);
                Image img = null;
                try {
                    img = Image.createImage(FileSystemStorage.getInstance().openInputStream(filePath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image_name[0] = System.currentTimeMillis() + ".jpg";
                jobIcon.setIcon(img);
                System.out.println(filePath);
                System.out.println(image_name[0]);

                try {
                         pathToBeStored[0] = FileSystemStorage.getInstance().getAppHomePath()+ image_name[0];
                        OutputStream os = FileSystemStorage.getInstance().openOutputStream(pathToBeStored[0]);
                        ImageIO.getImageIO().save(img, os, ImageIO.FORMAT_JPEG, 0.9f);
                        os.close();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
    }, Display.GALLERY_IMAGE);});



            ////////////Copied with URL Symfony
            Button myButton = new Button("Valider");
            myButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    ServiceProduit sp = new ServiceProduit();
                    ServiceEchange se  = new ServiceEchange();
                    String path = "C:/Users/omark/.cn1/"+image_name[0];
                   File file = new File(path);
                   sp.ajoutProduit(file);
                     

                }
            });


    fAjout.addAll(nomProduit,descProduit,opProduit,jobIcon,myButton,image);
    fAjout.show();

}

Solution

  • i resolved the problem, i modified the " Java Code ":

        MultipartRequest cr = new MultipartRequest();
        cr.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout");
        cr.setPost(true);
        String mime = "image/png";
        try {
            cr.addData("file", filePath, mime);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fichernom = System.currentTimeMillis() + ".png";
        cr.setFilename("file", fichernom);
    
        InfiniteProgress prog = new InfiniteProgress();
        Dialog dlg = prog.showInifiniteBlocking();
        cr.setDisposeOnCompletion(dlg);
        NetworkManager.getInstance().addToQueueAndWait(cr);