Retrofit 2 file down/upload

前端 未结 5 1745
栀梦
栀梦 2020-12-13 00:54

I\'m trying to down/upload a file with retrofit 2 but can\'t find any tutorials examples on how to do so. My code for downloading is:

@GET(\"documents/checko         


        
5条回答
  •  攒了一身酷
    2020-12-13 01:04

    Also I had this problem, This is how i try to solve my problem (RETROFIT 2 )

     //1. What We Need From Server ( upload.php Script )
        public class FromServer {
            String result;
        }
    
        //2. Which Interface To Communicate Our upload.php Script?
        public interface ServerAPI {
    
            @Multipart
            @POST("upload.php")//Our Destination PHP Script
            Call> upload(
                    @Part("file_name") String file_name,
                    @Part("file") RequestBody description);
    
             Retrofit retrofit =
                    new Retrofit.Builder()
                            .baseUrl("http://192.168.43.135/retro/") // REMEMBER TO END with /
                            .addConverterFactory(GsonConverterFactory.create())
                     .build();
        }
    
    
        //3. How To Upload
        private void upload(){
    
                ServerAPI api = ServerAPI.retrofit.create(ServerAPI.class);
    
                File from_phone = FileUtils.getFile(Environment.getExternalStorageDirectory()+"/aa.jpg"); //org.apache.commons.io.FileUtils
                RequestBody to_server = RequestBody.create(MediaType.parse("multipart/form-data"), from_phone);
    
                api.upload(from_phone.getName(),to_server).enqueue(new Callback>() {
                    @Override
                    public void onResponse(Call> call, Response> response) {
                        Toast.makeText(MainActivity.this, response.body().get(0).result, Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onFailure(Call> call, Throwable t) { }
                });
    
    
             }
    
    //4. upload.php
    "Done");
        print(json_encode($arr));
    ?>
    

提交回复
热议问题