Retrofit 上传图片
程序员文章站
2022-07-14 17:06:30
...
@Multipart
@POST("网址")
Call<ResponseBody> addGoods(@Part("uploadfile") RequestBody body);
File file=new File(pathImg);
RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
Call<ResponseBody> call = myInterface.addGoods(body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()) {
try {
String string = response.body().string();
if (!TextUtils.isEmpty(string)) {
callback.onSuccess(string);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onError(t.getMessage());
}
});
javaweb后端接收代码
记得在Servlet类名上添加注解
@MultipartConfig
Part part = request.getPart("uploadfile");
InputStream inputStream = part.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File("保存图片的文件夹路径", System.currentTimeMillis() + ".jpg"));
byte[] byt = new byte[1024];
int len;
while ((len = inputStream.read(byt)) != -1) {
outputStream.write(byt, 0, len);
}
outputStream.close();
inputStream.close();
上一篇: 关于移动端scroll不执行的问题
下一篇: Linux下gSoap的安装使用