4

アプリを構築していて、ある時点で画像をサーバーにアップロードする必要があります。画像をパラメーターとしてのみ配置すると、すべて完全に機能しますが、問題はテキストを追加しても何も起こらないことです。これが私のコードです

public int uploadFile(String sourceFileUri) {
      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); 
        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("username", username); 
          dos = new DataOutputStream(conn.getOutputStream());

          dos.writeBytes(twoHyphens + boundary + lineEnd); 
          dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                    + fileName + "\"" + lineEnd);
          dos.writeBytes(twoHyphens + boundary + lineEnd);

          dos.writeBytes("Content-Disposition: form-data; name=\"username\";filename=\""
                                    + username + "\"" + lineEnd);
          dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + 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 = "http://phpserver"+ture;


                       Toast.makeText(Friend.this, "Uploaded succesfully", 
                                    Toast.LENGTH_SHORT).show();
                       //new Post_test().execute();
                   }
               });                
          }    

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

     } catch (MalformedURLException ex) {

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

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

                 Toast.makeText(Friend.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() {

                 Toast.makeText(Friend.this, "Got Exception : see logcat ", 
                         Toast.LENGTH_SHORT).show();
             }
         });
         Log.e("Upload file to server Exception", "Exception : " 
                                          + e.getMessage(), e);  
     }
     dialog.dismiss();       

    return serverResponseCode; 
}

私は何を間違っていますか?

削除すると:

dos.writeBytes(twoHyphens + boundary + lineEnd);          
dos.writeBytes("Content-Disposition: form-data; name=\"username\";filename=\"" + 
                username + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);

画像がアップロードされるため、問題はテキスト投稿の追加方法にある可能性があります。何か助けはありますか?

4

2 に答える 2

1

これは私のために働く!! 今後はURLConnectionに調整します...

public int uploadFile(String sourceFileUri) {  

    String fileName=sourceFileUri;
    HttpURLConnection conn = null;
    DataOutputStream dos = null;  
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "------hellojosh";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024; 
    File sourceFile = new File(fileName); 
    Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);

    if (!sourceFile.isFile()) {                                
         Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);                
         runOnUiThread(new Runnable() {
            public void run() {             
                //messageText.setText("Source File not exist :"
                }
            });          
         return 0;  //RETURN #1
         }
    else{
        try{                

             FileInputStream fileInputStream = new FileInputStream(sourceFile);           
             URL url = new URL(upLoadServerUri);
             Log.v("joshtag",url.toString());

             // 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            s       
             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("file", fileName);                     
             conn.setRequestProperty("user", user_id));

             dos = new DataOutputStream(conn.getOutputStream());          
             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"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);
                    Log.i("joshtag","->");
                    }

             // 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().toString();              
             Log.i("joshtag", "HTTP Response is : "  + serverResponseMessage + ": " + serverResponseCode);  

             // ------------------ read the SERVER RESPONSE
             DataInputStream inStream;
             try {
                 inStream = new DataInputStream(conn.getInputStream());
                 String str;
                 while ((str = inStream.readLine()) != null) {
                     Log.e("joshtag", "SOF Server Response" + str);
                    }
                 inStream.close();
                }
             catch (IOException ioex) {
                Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
                }

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

             if(serverResponseCode == 200){ 
                //Do something                       
                }//END IF Response code 200  

            dialog.dismiss();
            }//END TRY - FILE READ      
        catch (MalformedURLException ex) {
            ex.printStackTrace();     
            Log.e("joshtag", "UL error: " + ex.getMessage(), ex);  
            } //CATCH - URL Exception

         catch (Exception e) {           
            e.printStackTrace();             
            Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
            } //

        return serverResponseCode; //after try       
        }//END ELSE, if file exists.
    }
于 2015-12-30T10:20:57.050 に答える