Retrofit2 上传图片(服务器端+Android端)

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

自己只用了这两个

先写一个接口,BaseUrl+Post =完整的Url.

@Part里面写了服务器端的(@RequestParam(value="upload_file") MultipartFile file ,value里面的值

 

服务器端

/**
     * @return
     */
    @RequestMapping(value = "uploadlicense.do")
    @ResponseBody
    public ServerResponse uploadlicense(@RequestParam(value="upload_file") MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file, path);
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;

        Map fileMap = Maps.newHashMap();
        fileMap.put("uri", targetFileName);
        fileMap.put("url", url);

        int storeid = adminoneMapper.getstoreidbyusername("yuyu");
        storeMapper.updatelicesepicture(storeid,url);
        return ServerResponse.createBySuccess(fileMap);
    }

Android端


import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface RetrofitService {

    @Multipart
    @POST("yuyu/storeByAdmin/uploadlicense.do")
    Call uploadEvaluation(@Part("upload_file\";filename=\"1.jpg") RequestBody file);

}
private void upload() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://ip地址:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitService service = retrofit.create(RetrofitService.class);
        File file = new File(Environment.getExternalStorageDirectory(), Const.licensepicture);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("image/jpg"), file);
        Call uploadPicture = service.uploadFileWithRequestBody(requestFile);
        uploadPicture.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.e(TAG, "onResponseonResponseonResponse: "+response.body().toString() );
                //Toast.makeText(uploadLicensePicture.this, (CharSequence) response.body(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.e(TAG, "onFailureonFailureonFailureonFailureonFailureonFailure: " );
            }
        });
    }

 

你可能感兴趣的:(Android,Retrofit)