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