我正在尝试使用okhttp3将所有类型的文件上传到服务器。我成功上传了小于2MB的文件但是对于大文件,上传停在中间位置。 代码是
public void uploadfile(String filePath)
{
File f = new File(filePath);
String filepaths = f.getAbsolutePath();
String content_type = getMimeType(f.getPath());
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.MINUTES)
.readTimeout(15, TimeUnit.MINUTES)
.writeTimeout(10, TimeUnit.MINUTES)
.build();
RequestBody fileBody = RequestBody.create(MediaType.parse(content_type),f);
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploadedfile","nullify"+sourceFilePath.substring(sourceFilePath.lastIndexOf(".")),fileBody).build();
RequestBody requestBody = ProgressHelper.withProgress(body, new ProgressListener() {
@Override
public void onProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
dialog.setProgress((int)(100 * percent));
}
});
Request request = new Request.Builder()
.url("https://Somewhere/save_file.php")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
response.close();
dialog.dismiss();
}
if (!response.isSuccessful())
{
throw new IOException("Error:"+response);
}
} catch (IOException e) {
e.printStackTrace();
}
}