大家好。我没有使用android的经验,所以我遇到了这个问题,我无法以任何方式解决。
问题是无法从 android 发送 115MB 的视频文件。
它是如何表达的:
更准确地说,在 115Mb 中,有 52Mb 进入服务器,传输停止在那里。服务器返回 code = 200 并写入它已收到一个 52MB 的文件。虽然从应用程序发送了一个 60MB 的文件 - 没问题!
下面是使用的代码示例。
private class UploadImageTask extends AsyncTask<String, Void, List<File>> {
protected List<File> doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
resultTextView.append("\nuploading started.....");
}
});
for (File file : fileList){
uploadFile(file);
}
return null; //loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(List<File> list) {
resultTextView.append("\nUPLOAD -> STATE: " + MultipartUtility.status);
resultTextView.append("\nUPLOAD -> END");
Toast.makeText(getApplicationContext(), "UPLOAD: -> END", Toast.LENGTH_LONG).show();
}
}
public int uploadFile(File sourceFile) {
final String fileName = sourceFile.getName();
HttpsURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable;//, bufferSize;
byte[] buffer;
int maxBufferSize = 4 * 1024 * 1024;
long fileSize = sourceFile.length();
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"
//+ uploadFilePath + "" + uploadFileName);
+ sourceFile.getName()
);
runOnUiThread(new Runnable() {
public void run() {
resultTextView.append("Source File not exist :"
//+uploadFilePath + "" + uploadFileName);
+ fileName
);
}
});
return 0;
}
else
{
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpsURLConnection) url.openConnection();
conn.setConnectTimeout(360000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "bearer " + token.getAccess());
conn.setRequestProperty("Connection", "Keep-Alive" );
conn.setRequestProperty("ENCTYPE", "multipart/form-data" );
conn.setRequestProperty("Transfer-Encoding","chunked" );
conn.setChunkedStreamingMode(1024);
//conn.setRequestProperty("file", sourceFile.getPath());
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd
);
dos.writeBytes(lineEnd);
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);
sendBytes = sendBytes + bytesRead;
runOnUiThread(new Runnable() {
public void run() {
sizeTextView.setText("BUFFER-SIZE: " + bufferSize + "\nNAME: " + fileName + "\nSIZE: " + sendBytes);
}
});
}
// 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() {
resultTextView.append("\nUPLOAD-CODE: " + serverResponseCode);
String msg = "\nFile Upload Completed.\n\n See uploaded file here : \n\n"
+ fileName;
resultTextView.append(msg);
Toast.makeText(UploadActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
resultTextView.append("MalformedURLException Exception : check script url.");
Toast.makeText(UploadActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
resultTextView.append("Got Exception : see logcat ");
Toast.makeText(UploadActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload-Exception", "Exception : "
+ e.getMessage(), e);
}
return serverResponseCode;
} // End else block
}
AndroidManifest
android:allowBackup="true"
android:hardwareAccelerated="false"
android:largeHeap="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
测试服务器时,没有发现任何问题!相同的文件传输方法在带有 -Xmx10M 的普通控制台模式(机器人)下效果很好;
服务器:
@PostMapping("/{id}/file")
public void uploadFile(@PathVariable("id") Request request, @RequestParam("file") MultipartFile[] files){
log.info("==========================================");
log.info("===uploadFile2:start:" + request.getId());
if (files.length<1) {
throw new StorageException("No Files");
}
try {
FileUpload.saveUploadedFiles(Arrays.asList(files), "/request/1266123/");
} catch (IOException e) {
throw new StorageException("File upload error", e);
}
log.info("Successfully uploaded - " + files.length);
}
提前感谢您的回复。
PS / 感觉好像只从原始流中读取了52MB,然后发送。
此代码完全有效。问题出在文件本身,事实证明,文件已损坏,重达 52MB