Retiofit with RxJava single file upload

1, Upload through interface definition

For the defined interface method, it should be noted that this method no longer has the @ FormUrlEncoded annotation, but has changed to @ Multipart. Later, you only need to add Part to the parameter. You may ask, what's the difference between Part and Field here? In fact, in terms of function, it's just that the client sends a request to the server to carry parameters in different ways, and the former can carry more parameters, including data flow. Because of this, we can upload files in this way:

@Part("file\"; filename=\"avatar.jpg") RequestBody file

File is the field name (unique, changed according to the document) filename is the file name (defined casually)

public interface RetiofitVpi {
    //Upload file
    Observable<FileBean> uploadFile(@Query("uid") String uid,
                                    @Part("file\"; filename=\"avatar.jpg") RequestBody file);

2. We will give the usage of this interface as follows:

Parameter: file is a file

"3381" is a parameter of the document (changed according to the interface document)

public void uploadFiles(File file){
        //The agent mode generates the instantiation object of the corresponding server
        RetiofitVpi server = RetiofitUtils.getInstance().create(RetiofitVpi.class);
        //Create RequwstBody object
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        //Scheduling tasks and listening in RxJava mode
                .subscribe(new Consumer<FileBean>() {
                    public void accept(FileBean nicknameBean) throws Exception {
                        if (nicknameBean!=null){
                        }else {

                }, new Consumer<Throwable>() {
                    public void accept(Throwable throwable) throws Exception {

Posted on Thu, 30 Apr 2020 03:45:57 -0700 by bob2588