Android post data along with file using multipart data

I am trying to send variable with HTTP post using multipart form data. I successfully sent file it uploading to server flawlessly but i am unable to send variables in the same request. Below is my sample code. Thanks in advance

public int uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname) {


      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "rn";
      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 :"
                                + "" + uploadFileName);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           + "" + uploadFileName);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               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); 
                conn.setRequestProperty("name", name); 
                conn.setRequestProperty("price", price); 
                conn.setRequestProperty("category", category); 
                conn.setRequestProperty("album", albumid); 
                conn.setRequestProperty("artist_id", artistid); 
                conn.setRequestProperty("album_name", albumname); 
               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);

               // 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);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed.nn See uploaded file here : nn"
                                          +uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(UploadToServer.this, "File Upload Complete."+JsonResponse, 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

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

          } catch (MalformedURLException ex) {

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

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(UploadToServer.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(UploadToServer.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : " 
                                               + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     } 

I am sending the variable here

conn.setRequestProperty("uploaded_file", fileName); 
            conn.setRequestProperty("name", name); 
            conn.setRequestProperty("price", price); 
            conn.setRequestProperty("category", category); 
            conn.setRequestProperty("album", albumid); 
            conn.setRequestProperty("artist_id", artistid); 
            conn.setRequestProperty("album_name", albumname); 
           dos = new DataOutputStream(conn.getOutputStream());

Finally, after a lot of hit and trial i got my code working. Posting it as an answer for anyone who might want to do same task in android

   public int uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname) {


      String fileName = sourceFileUri;

      DataOutputStream dos = null;  
      String lineEnd = "rn";
      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 :"
                                + "" + uploadFileName);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           + "" + uploadFileName);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               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); 
                conn.setRequestProperty("name", name); 
                conn.setRequestProperty("price", price); 
                conn.setRequestProperty("category", category); 
                conn.setRequestProperty("desc", description); 
                    conn.setRequestProperty("album", albumid); 
                conn.setRequestProperty("artist_id", artistid); 
                conn.setRequestProperty("album_name", albumname); 
               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);

               // 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);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                             BufferedReader br = null;
                            try {
                                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                             StringBuilder sb = new StringBuilder();
                             String line;

                                while ((line = br.readLine()) != null) {
                                     sb.append(line+"n");
                                 }
                                br.close();
                                 sb.toString();
                                String msg = "File Upload Completed.nn See uploaded file here : nn"
                                          +sb.toString();

                            messageText.setText(msg);

                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                              Toast.makeText(UploadToServer.this, "File Upload Complete."+JsonResponse, 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

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

          } catch (MalformedURLException ex) {

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

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(UploadToServer.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(UploadToServer.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : " 
                                               + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     } 

And for server side i am using php so i got all the key values in $SERVER, but beware all of ur keys will be capitalized with HTML concatenated with it automatically like i am sending album_name but on server it $_SERVER['HTTP_ALBUM_NAME'];

$albumname=$_SERVER['HTTP_ALBUM_NAME'];

I will suggest you to use okhttp. You can use it like that;

public void uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname, byte[] data) {
    MediaType MEDIA_TYPE_MP3 = MediaType.parse("audio/mpeg");
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("uploaded_file", filename,
                    RequestBody.create(MEDIA_TYPE_MP3, data))
            .addFormDataPart("name", name)
            .addFormDataPart("price", price)
            .addFormDataPart("category", category)
            .addFormDataPart("album", album)
            .addFormDataPart("category", category)
            .addFormDataPart("artist_id", artistid)
            .addFormDataPart("album_name", albumname)
            .build();
    com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
            .url(upLoadServerUri)
            .post(requestBody)
            .build();
    okHttpClient.newCall(request).enqueue(new com.squareup.okhttp.Callback() {

        @Override
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {

        }

        @Override
        public void onResponse(final com.squareup.okhttp.Response response) throws IOException {

        }
    });
}
链接地址: http://www.djcxy.com/p/22182.html

上一篇: nginx上传客户端

下一篇: Android使用多部分数据发布数据以及文件