Skip to content
Advertisement

Sending Image files and Text from android app java HttpURLConnection multipart form-data

Hi I am trying to upload a file and a text, using multipart form-data HttpURLConnection java, sample of code below:

String boundary = UUID.randomUUID().toString();
    final String LINE_FEED = "rn";
    OutputStream outputStream;
    PrintWriter writer;

URL url_upload = new URL(url_api );

HttpURLConnection conn = (HttpURLConnection) url_upload.openConnection();
            conn.setUseCaches(false);
            conn.setDoOutput(true); // indicates POST method
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            
            conn.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
            conn.setRequestProperty("Connection", "Keep-Alive");



            outputStream = conn.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
            //DataOutputStream request = new DataOutputStream(conn.getOutputStream());

            //Username
            writer.append("--").append(boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name="" + "Username" + """)
                    .append(LINE_FEED);
            writer.append("Content-Type: text/plain; charset=").append("UTF-8").append(
                    LINE_FEED);
            writer.append(LINE_FEED);
            writer.append(Username).append(LINE_FEED);
            writer.flush();

            //Password
            writer.append("--").append(boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name="" + "Password" + """)
                    .append(LINE_FEED);
            writer.append("Content-Type: text/plain; charset=").append("UTF-8").append(
                    LINE_FEED);
            writer.append(LINE_FEED);
            writer.append(Password);
            writer.flush();
            writer.append(LINE_FEED);


            if(Food_image_file_name != null)
            {
                Log.i("File:", String.valueOf(file1));
                

                writer.append("--").append(boundary).append(LINE_FEED);
                writer.append("Content-Disposition: form-data; name="" + "file1" + ""; filename="").append(file1.getName()).append(""")
                        .append(LINE_FEED);
                writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(file1.getName()))
                        .append(LINE_FEED);
                writer.append("Content-Transfer-Encoding: binary");
                writer.append(LINE_FEED);
                writer.flush();
                writer.append(LINE_FEED);

                FileInputStream inputStream = new FileInputStream(String.valueOf(file1.toPath()));
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
                inputStream.close();
                writer.append(LINE_FEED);
                writer.flush();


writer.append(LINE_FEED).flush();
            writer.append("--").append(boundary).append("--").append(LINE_FEED);
            writer.close();


additional details: I/File:: /storage/emulated/0/DCIM/100ANDRO/DSC_0117.JPG I/Api response: 400, Bad Request

Note: I tested server from postman, and it working with no issues with Postman, the files where uploaded successful to the server from postman.

This link is another post of a sample of a web api i am using to read the request: link_here

Update: I had to modify my web api a bit as i wasn’t using properly, the code works fine now

I/File:: /storage/emulated/0/Pictures/Viber/IMG-8bf36fec3b3c01df23c7faf763e2eac7-V.jpg
I/Boundary: ****
I/Image Content type: image/jpeg

and in Blob images Azure, i see that the image it is not visible, it is corrupted.

so my last issue was in write of the image, correct code below, works like a charm now 😉:

writer.append("--").append(boundary).append(LINE_FEED);
                writer.append("Content-Disposition: form-data; name="" + "file1" + ""; filename="").append(file1.getName()).append(""")
                        .append(LINE_FEED);
                writer.append("Content-Type: ").append(mimeType)
                        .append(LINE_FEED);
                writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
                writer.append(LINE_FEED);
                writer.flush();

Advertisement

Answer

so my last issue was in write of the image, correct code below, works like a charm now ;):

writer.append("--").append(boundary).append(LINE_FEED);
                writer.append("Content-Disposition: form-data; name="" + "file1" + ""; filename="").append(file1.getName()).append(""")
                        .append(LINE_FEED);
                writer.append("Content-Type: ").append(mimeType)
                        .append(LINE_FEED);
                writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
                writer.append(LINE_FEED);
                writer.flush()

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement