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,但不通過服務器發送文件。 我附上郵遞員快照。授權碼在標題中發送。
請幫
你有任何錯誤日誌? – Yazan
不,只有這樣:E/Debug:寫入文件 /System.out:[OKHttp] sendRequest >> System.out:[OkHttp] sendRequest << E/Debug:Server Response {「status」:true} –
'bytesRead = bytesAvailable;'這當然不好。引入一個'totalbytesread'和'totalbyteswritten'變量,然後與bytesAvailable和文件大小進行比較。請注意四個值。 – greenapps