使用改造版android上传文件?

时间:2018-06-22 17:06:31

标签: android file retrofit multipartform-data

我正在尝试通过翻新的方式上传视频文件,但出现以下错误

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);

1 个答案:

答案 0 :(得分:0)

在您的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();
        }
    }