1

I have tried to post multiple file to web service. But, single file post working multiple file post not working.

Please help me any one. How to implement that feature.

I have tried the below code. Please check it.

    String fileName = sourceFileUri;
 String fileName1 = sourceFileUri1;    
// fileName1 - how to post to web service

HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {
        dialog.dismiss();
        Log.e("uploadFile", "Source File not exist :" + imagepath);
        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :" + imagepath);
            }
        });
        return 0;
    } else {
        try {
            // open a URL connection to the Servlet
            URL url = new URL(upLoadServerUri);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file[]", fileName);

            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file[]\";filename=\""
                    + fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

            InputStream is = conn.getInputStream();
            // retrieve the response from server
            int ch;

            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            String s = b.toString();
            Log.i("Response", s);

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(MainActivity.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(MainActivity.this,
                            "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    }
0

2 Answers 2

1

If you want to pass an array of FileBody, you can try it like,

     reqEntity.addPart("file[]["+i+"]", bab);

This will generate params like

     file=>[{"1" => "File" },{"2" => "File"}..]

Hope it clarifies your doubt.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Bharath Thanks for reply, But what I need is, "conn.setRequestProperty("uploaded_file[]", fileName);" here how to add more than one file. "fileName" is string. "setRequestProperty" not accept array. If possible here to add more file.
1

I got solution. I have used like as below. It's working.

public void uploadFileNew(ArrayList<String>IMAGEPTHLIST, ArrayList<String>IMAGENAMELIST) {
         try {
             HttpClient httpClient = new DefaultHttpClient();
             HttpPost postRequest = new HttpPost(upLoadServerUri);
             ByteArrayBody bab;
             ByteArrayOutputStream bos;
             Bitmap bm;
             MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
             for(int i = 0 ; i< IMAGEPTHLIST.size() ; i++) {
                 bm = BitmapFactory.decodeFile(IMAGEPTHLIST.get(i));
                 bos = new ByteArrayOutputStream();
                  bm.compress(CompressFormat.PNG, 100, bos);
                  byte[] data = bos.toByteArray();
                 bab = new ByteArrayBody(data, IMAGENAMELIST.get(i));                      
                 reqEntity.addPart("file["+i+"]", bab);
             }
             reqEntity.addPart("cat_id", new StringBody("123"));
             reqEntity.addPart("name", new StringBody("Android test"));
             postRequest.setEntity(reqEntity);                           
             HttpResponse response2 = httpClient.execute(postRequest);                           
             BufferedReader reader = new BufferedReader(new InputStreamReader(response2.getEntity().getContent(), "UTF-8"));

             String sResponse;
             StringBuilder s = new StringBuilder();

             while ((sResponse = reader.readLine()) != null) {
                 s = s.append(sResponse);
             }
             System.out.println("===="+s.toString());         
         } catch (Exception e) {
             e.printStackTrace();
         }           
         dialog.dismiss();  
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.