Skip to content

Android OkHttp Retrofit 上传文件

单文件上传,无参数的情况

服务接口编写

    /**
     * 上传文件
     */
    @Multipart
    @POST("applog/upload")
    Observable<UploadFileResp> uploadFile(@Part MultipartBody.Part file);

构建MultipartBody.Part

    File f = new File("aa.txt");
    RequestBody requestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), f);
    MultipartBody.Part part =
            MultipartBody.Part.createFormData("file", f.getName(), requestBody);

子线程中调用上传

commonService.uploadFile(part).subscribe(new Observer<UploadFileResp>() {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(UploadFileResp resp) {
        if (resp.getCode() == RESP_GOOD_CODE) {
            boolean r = f.delete();
            LL.dn(TAG, r + " 上传log成功 : " + f.getName());

        }
    }

    @Override
    public void onError(Throwable e) {
        Log.e(TAG, "上传log文件 [" + f + "] onError: ", e);
        LL.en(TAG, e.getMessage());
    }

    @Override
    public void onComplete() {

    }
});