2013-10-29 3 views
1

왜 자바에서 서버로 게시물을 업로드하고 다음 코드를 사용합니다.Bystes 예상과 자바에서 POST를 보내는 일치하지 않습니다

나는

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

        if (!sourceFile.isFile()) { 

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

         return 0; 

        } 
        else 
        { 
         try { 

       FileInputStream fileInputStream = new FileInputStream(sourceFile); 
          URL url = new URL(upLoadServerUri); 
          int total = (int) sourceFile.length(); 
          // Open a HTTP connection to the URL 
          conn = (HttpURLConnection) url.openConnection(); 
          conn.setFixedLengthStreamingMode(total); 
          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("mail", MAIL); 
          conn.setRequestProperty("OS", "1"); 
          conn.setRequestProperty("LANG", "ES"); 

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

바이트가 excpected과 일치하지 않는 발송에 실패 편집 기능의 정상 코드의 나머지 부분을 추가 한? 나는 그것이 왜 일어나는 지 이해하지 못한다.

Exception : expected 589715 bytes but received 589840 
java.io.IOException: expected 589715 bytes but received 589840 
at libcore.net.http.FixedLengthOutputStream.write(FixedLengthOutputStream.java:39) 
at java.io.DataOutputStream.write(DataOutputStream.java:98) 
at com.androidexample.uploadtoserver.UploadToServer.uploadFile(UploadToServer.java:152) 
at com.androidexample.uploadtoserver.UploadToServer$1.run(UploadToServer.java:62) 
at java.lang.Thread.run(Thread.java:856) 

답변

2

콘텐츠를 스트림에 쓰는 중 표시하지 않습니다. 나는 당신이 경계 바이트 길이뿐만 아니라 파일 길이를 설명 할 필요가 있다고 생각한다. 참고 : int로 전송할 필요는 없습니다. HttpURLConnection.setFixedLengthStreamingMode(long) 방법이 있습니다. 당신은 또한보고 싶어 할 수도 있습니다 this other thread.

편집 : 예외에 따르면, 당신은 125 바이트 (589840 - 589715) 떨어져 있습니다. 2x 경계 길이 (결과 문자열 twoHyphens + boundary + lineEnd의 바이트 수) + "Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"" + fileName + "\"" + lineEnd 바이트가 125 바이트인지 확인하십시오. 그렇다면 추가 정보가 필요합니다.

+0

내 코드의 나머지 부분을 추가했습니다. MadConan – David

+1

연결을 쓰고있는 위치가 여전히 표시되지 않습니다. 그것이 중요합니다. 당신은 X 바이트를 쓸 것이지만 Y를 쓰게 될 것이라고 말할 수있다. conn.connect()와 같은 코드는 어디에 있는가? OutputStream out = conn.getOutputStream(); ... out.write (byteArary, 0, bytesArray.length];'등 – MadConan

+0

죄송합니다. 수정했습니다. – David

관련 문제