2016-06-22 26 views
-1

マルチパートフォームデータを使用してHTTPポストで変数を送信しようとしています。私は正常にサーバーにアップロードするファイルを正常に送信しましたが、同じリクエストで変数を送信できません。以下は私のサンプルコードです。おかげで事前マルチパートデータを使用してファイルと一緒にAndroidポストデータ

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 = "\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 :" 
           + "" + 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.\n\n See uploaded file here : \n\n" 
              +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()); 
+0

私の投稿を投票する理由は何ですか?何か問題がありますか? – farhan678

答えて

1

最後に、多くのヒットとトライアルの後、自分のコードが動作しています。アンドロイド

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 = "\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 :" 
           + "" + 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.\n\n See uploaded file here : \n\n" 
              +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を使用していますが、ウルすべてのキーをします用心に同じタスクを実行したい場合があります誰のための答えとして、それを投稿アルバム名を送信しているようにHTMLで大文字にする必要がありますが、サーバー上では$ _SERVER ['HTTP_ALBUM_NAME'];

$albumname=$_SERVER['HTTP_ALBUM_NAME']; 
0

変数を送信しています私はあなたが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 { 

     } 
    }); 
} 
+0

ありがとうございますが、私はサーバーに.mp3ファイルをアップロードする必要があります。投稿することもできますか? – farhan678

+0

ありがとう。やってみます – farhan678

関連する問題