2016-06-22 13 views
-1

Ich versuche, Variable mit HTTP-Post mit mehrteiligen Formulardaten zu senden. Ich habe die Datei, die es hochgeladen hat, erfolgreich zum Server geschickt, aber ich kann keine Variablen in derselben Anfrage senden. Unten ist mein Beispielcode. Vielen Dank im VorausAndroid Post-Daten zusammen mit Datei mit Multipart-Daten

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 
    } 

Ich schicke die Variable hier

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

Warum Leute meinen Beitrag abstimmen? Ist etwas nicht in Ordnung? – farhan678

Antwort

1

Endlich, nach einer Menge von Hit und Test habe ich meinen Code funktioniert. Posting es als eine Antwort für alle, die gleiche Aufgabe 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 = "\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 
    } 

Und für Server-Seite zu tun, könnte ich will php bin mit so i in $ SERVER alle wichtigen Werte erhalten, aber alle ur Schlüssel passen wird mit HTML groß geschrieben werden, das automatisch mit it verbunden wird, wie ich album_name sende, aber auf dem Server es $ _SERVER ['HTTP_ALBUM_NAME'];

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

Ich schlage vor, Sie okhttp zu verwenden. Du kannst es so benutzen;

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

Danke, aber ich muss .mp3-Datei zum Server hochladen. Wird es in der Lage sein, es auch zu posten? – farhan678

+0

Vielen Dank. Ich werde es versuchen – farhan678

Verwandte Themen