2016-03-15 103 views
2

PostmanSnapshot安卓:在服務器

HttpURLConnection conn = null; 
    DataOutputStream dos = null; 
    DataInputStream inStream = null; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 
    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 
    try { 
    FileInputStream fileInputStream = new FileInputStream(new File(selectedPath)); 
    URL url = new URL(UPLOAD_URL); 
    conn = (HttpURLConnection) url.openConnection(); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setRequestMethod("POST"); 
    conn.setRequestProperty("authToken", authToken); 
    conn.setRequestProperty("Connection", "Keep-Alive"); 
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 

    dos = new DataOutputStream(conn.getOutputStream()); 
    dos.writeBytes(lineEnd+twoHyphens + boundary + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name:\"photo-0\";filename=\"" + selectedPath + "\"" + lineEnd); 
    dos.writeBytes("Content-Type: multipart/form-data"+lineEnd+lineEnd); 
    dos.writeBytes(lineEnd); 
    bytesAvailable = fileInputStream.available(); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    buffer = new byte[bufferSize]; 

    bytesRead = bytesAvailable; 

    while (bytesRead > 0) { 
    dos.write(buffer, 0, bufferSize); 
    bytesAvailable = fileInputStream.available(); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    } 

    dos.writeBytes(lineEnd); 
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
    fileInputStream.close(); 
    dos.flush(); 
    dos.close(); 

    } catch (MalformedURLException ex) { 
    Log.e("Debug", "error: " + ex.getMessage(), ex); 
    } catch (IOException ioe) { 
    Log.e("Debug", "error: " + ioe.getMessage(), ioe); 
    } 
    try { 
    inStream = new DataInputStream (conn.getInputStream()); 
    String str; 

    while ((str = inStream.readLine()) != null) 
    { 
    Log.e("Debug","Server Response "+str); 
    } 
    inStream.close(); 

    } 
    catch (IOException ioex){ 
    Log.e("Debug", "error: " + ioex.getMessage(), ioex); 
    } 

此代碼是從Android應用程序上傳服務器上的文件上傳文件。 運行代碼時服務器狀態爲true,但不通過服務器發送文件。 我附上郵遞員快照。授權碼在標題中發送。

請幫

+0

你有任何錯誤日誌? – Yazan

+0

不,只有這樣:E/Debug:寫入文件 /System.out:[OKHttp] sendRequest >> System.out:[OkHttp] sendRequest << E/Debug:Server Response {「status」:true} –

+0

'bytesRead = bytesAvailable;'這當然不好。引入一個'totalbytesread'和'totalbyteswritten'變量,然後與bytesAvailable和文件大小進行比較。請注意四個值。 – greenapps

回答

1

我發現了一些東西,可能會幫助誰正在尋找同樣的問題。 它正在工作。我在做錯的是在while循環中。

public class MultipartUtility { 
private final String boundary; 
private static final String LINE_FEED = "\r\n"; 
private HttpURLConnection httpConn; 
private String charset; 
private OutputStream outputStream; 
private PrintWriter writer; 

public MultipartUtility(String requestURL, String charset) 
     throws IOException { 
    this.charset = charset; 
    boundary = "===" + System.currentTimeMillis() + "==="; 
    URL url = new URL(requestURL); 
    httpConn = (HttpURLConnection) url.openConnection(); 
    httpConn.setUseCaches(false); 
    httpConn.setDoOutput(true); // indicates POST method 
    httpConn.setDoInput(true); 
    httpConn.setConnectTimeout(10000);//10 sec timeout 
    httpConn.setRequestProperty("Content-Type","multipart/form-data;  boundary=" + boundary); 
    httpConn.setRequestProperty("authToken", LoginActivity.authenticationToken); 
    outputStream = httpConn.getOutputStream(); 
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); 
} 

public void addFilePart(String fieldName, File uploadFile) throws IOException { 
    String fileName = uploadFile.getName(); 
    writer.append("--" + boundary).append(LINE_FEED); 
    writer.append("Content-Disposition: form-data; name=\"" + fieldName+ "\"; filename=\"" + fileName + "\"").append(LINE_FEED); 
    writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED); 
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 
    writer.append(LINE_FEED); 
    writer.flush(); 
    FileInputStream inputStream = new FileInputStream(uploadFile); 
    byte[] buffer = new byte[4096]; 
    int bytesRead = -1; 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outputStream.write(buffer, 0, bytesRead); 
    } 
    outputStream.flush(); 
    inputStream.close(); 
    writer.append(LINE_FEED); 
    writer.flush(); 
} 

public String finish() throws IOException { 
    StringBuilder sb = new StringBuilder(); 
    writer.append(LINE_FEED).flush(); 
    writer.append("--" + boundary + "--").append(LINE_FEED); 
    writer.close(); 
    int status = httpConn.getResponseCode(); 
    if (status == HttpURLConnection.HTTP_OK) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     reader.close(); 
     httpConn.disconnect(); 
    } else { 
     throw new IOException("Server returned non-OK status: " + status); 
    } 
    return sb.toString(); 
} 

}

+0

您應該爲您找到的代碼提供歸屬。 (似乎來自[這裏](http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically)。) – Mogsdad

+0

@Mogsdad有很多資源提供此代碼。其實我發現這個在stackoverflow答案。 –

+0

很棒... _which_答案? (他們缺乏歸因是一個不同的問題。)但是更重要的是,你的問題可能是重複的,正確的做法是把它作爲這個問題的重複。那麼具有相同問題的未來人將會找到他們的答案。 – Mogsdad