参考Retrofit基础上传 第一MainActivity类 Retrofit retrofitUpload; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); retrofitUpload = new Retrofit.Builder() .baseUrl("http://192.168.1.8:8080/UploadFile/") .addConverterFactory(GsonConverterFactory.create()) .build(); } @OnClick(R.id.buton_bu) public void onViewClicked() { file_img(); } //文件上传 //单文件上传携带参数(使用注解@Multipart和@Part),需要在手机SD卡目录下的Pictures文件夹下添加img.png图片 private void file_img(){ APIWrapper service = retrofitUpload.create(APIWrapper.class); File file = new File(Environment.getExternalStorageDirectory() + "/Pictures", "img.png"); //设置Content-Type:application/octet-stream RequestBody photoRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //设置Content-Disposition:form-data; name="photo"; filename="xuezhiqian.png" MultipartBody.Part photo = MultipartBody.Part.createFormData("photo", file.getName(), photoRequestBody); //添加参数用户名和密码,并且是文本类型 RequestBody userName = RequestBody.create(MediaType.parse("text/plain"), "nba"); RequestBody passWord = RequestBody.create(MediaType.parse("text/plain"), "666"); Call<User> loadCall = service.postImgApi(photo, userName, passWord); loadCall.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { Log.e("APP", response.body().getImgUri()); } @Override public void onFailure(Call<User> call, Throwable t) { t.printStackTrace(); } }); }
第二 APIWrapper类
public interface APIWrapper { @Multipart @POST("/file/img") //文件上传使用MultipartBody.Part对象 Call<User> postImgApi(@Part MultipartBody.Part photo, @Part("username") RequestBody username, @Part("password") RequestBody password); }
第三User
public class User { private String ImgUri; private String TextFile; public User() { } public String getTextFile() { return TextFile; } public void setTextFile(String textFile) { TextFile = textFile; } public String getImgUri() { return ImgUri; } public void setImgUri(String ImgUriUri) { this.ImgUri = ImgUriUri; } }