1

I wanna 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 paramatre 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();

}
Omar Krichen
  • 163
  • 1
  • 2
  • 12
  • 1
    Possible duplicate of [Java Post request with form data](https://stackoverflow.com/questions/45687553/java-post-request-with-form-data) have a look at that. when submitting files, php isn't very tolerant when it comes to form encoding. in all cases, see what arrives in your symfony app (postman vs. java app) – Jakumi May 04 '19 at 20:47
  • thank you for your answer. These are only with String parameter, but i wanna an Image – Omar Krichen May 04 '19 at 21:32
  • that's what I was saying. when you want to upload a file, and the webserver is running php, it'll only accept the file, when you send it with the right form-encoding (since the file is still part of a form submission, since you effectively fake a html form submission) see https://www.php.net/manual/en/features.file-upload.post-method.php for some glorious examples, the second note on that page however, is relevant.. – Jakumi May 04 '19 at 21:35

2 Answers2

1

Try the x-www-url-form-encoded. If that works then use MultipartRequest to submit binary data to the server. It implicitly handles form encode submission for you. If something doesn't work use the network monitor tool in Codename One to inspect the outgoing request/response which often provide helpful information about the process.

This isn't correct:

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

You're submitting a URL using the GET style argument passing. You need to submit the date of the image and not the image itself. You need to use addArgument() or addData() etc. to include the content in the request.

Shai Almog
  • 51,749
  • 5
  • 35
  • 65
  • i didn't understant what do u mean with x-www-url-form-encoded, yesterday i used `addArgument()` but it didn't work – Omar Krichen May 07 '19 at 08:07
0

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);
Omar Krichen
  • 163
  • 1
  • 2
  • 12