首页 > 解决方案 > 使用改造安卓上传文件?

问题描述

我正在尝试使用 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);

标签: androidfileretrofitmultipartform-data

解决方案


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

推荐阅读