android - 使用改造安卓上传文件?
问题描述
我正在尝试使用 multipart by retrofit 上传视频文件,但我收到以下错误作为响应
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=serverurl/Upload/Videos/}
这是我的文件上传代码
void uploadVideo(String videoPath) {
dialog.show();
File videoFile = new File(videoPath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoPath);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("file", videoFile.getName(), requestFile);
apiCall.uploadVideoToServer(presenter.getUserInfo().getUploadVideoPath(), vFile).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
dialog.dismiss();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
dialog.dismiss();
}
});
}
这是我将文件上传到的路径
http://serverurl.com/Upload/Videos/
有人可以告诉我我的代码有什么问题吗?
Retrofir API 接口
@Multipart
@POST
Call<String> uploadVideoToServer(@Url String url, @Part MultipartBody.Part video);
解决方案
在您的 api 服务接口中:
@Multipart
@POST("Upload/Videos") // *** DONT FORGET UR END POINT HERE ***
Call<urmodel> uploadVideoToServer(@PartMap Map<String, RequestBody> map);
并编写一个方法来上传你的视频文件,如下所示:
private void uploadVideoToServer(String path) {
File videoFile = new File(path);
if (videoFile.exists()) {
//create request body
Map<String, RequestBody> map = new HashMap<>();
RequestBody requestBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
map.put("video\"; filename=\"" + videoFile.getName() + "\"", requestBody);
//make call
Call<urmodel> call = mTService.uploadVideoToServer(map);
call.enqueue(new Callback<urmodel>() {
@Override
public void onResponse(Call<urmodel> call, Response<urmodel> response) {
if (response.isSuccess()) {
// DO SOMETHING
} else {
// DO SOMETHING
}
}
@Override
public void onFailure(Call<urmodel> call, Throwable t) {
//occur when fail to deserialize || no network connection || server unavailable
Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getBaseContext(), "can not upload file since the file is not exist :|", Toast.LENGTH_SHORT).show();
}
}
推荐阅读
- c++ - Visual Studio 中的 .hint 文件是什么?
- c++builder - 在运行时在 C++ Builder 中的 StringGrid 底部添加新条目
- python - 在两个不同的数据框Python中匹配正则表达式
- python-3.x - 在 Dockerfile 上设置环境变量,烧瓶服务器不起作用
- timer - Camel - 使用 TIMER 组件池化数据库时,如何使用 java dsl 停止骆驼路线?
- java - 仅当存在可选项时如何应用条件?
- python - 在 Python3.8 的多进程 SharedMemory 中共享字节对象
- python - 如何对具有非数字值的数据框进行分组和旋转
- c# - Asp.Net Web API 2:如何让数据绑定在控制器方法中使用正确的数据类型?
- xamarin.forms - 具有 ReactiveUI 的 Xamarin 表单 - 对 xaml.g.cs 的更改丢失,由 ReactiveUI 错误引起