Search code examples
androidhttpconnection

Android post file array


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;

    }

Solution

  • 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();  
         }