Android使用多部分数据发布数据以及文件

我正尝试使用多部分表单数据发送带有HTTP post的变量。 我成功发送文件上传到服务器完美,但我无法发送相同的请求中的变量。 以下是我的示例代码。 提前致谢

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 
     } 

我在这里发送变量

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

最后,经过大量的热门和试用,我得到了我的代码工作。 发布它作为任何人可能想要在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 
     } 

而对于服务器端我使用的PHP,所以我得到了所有的关键值在$ SERVER,但要注意所有的密钥将大写与HTML自动连接,就像我发送album_name,但在服务器上$ _SERVER ['HTTP_ALBUM_NAME'] ;

$albumname=$_SERVER['HTTP_ALBUM_NAME'];

我会建议你使用okhttp。 你可以这样使用它;

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/22181.html

上一篇: Android post data along with file using multipart data

下一篇: POST multipart/form