首先在buid.gradle中添加okhttp的依赖,需要有网络权限
<uses-permission android:name="android.permission.INTERNET" />
implementation 'com.squareup.okhttp3:okhttp:3.13.1'
1 Android端:
private void upload(ArrayList<ImageItem> selImageList) {// selImageList 包含图片路径的list
Logs.i("upload() ");
if (selImageList != null) {
OkHttpClient okHttpClient = new OkHttpClient();
for (int i = 0; i < selImageList.size(); i++) {
File file = new File(selImageList.get(i).path); //根据路径创建file对象
Logs.i("file.getName() "+file.getName());
// 后台通过List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");将上传的图片取出
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM) //表单上传文件
.addFormDataPart("files", //
file.getName(),
RequestBody.create(MediaType.parse("image/jpeg"), file)
);
//post时的参数,后台通过request.getParameter("specialname").toString() 取出
builder.addFormDataPart("specialname",file.getName());
builder.addFormDataPart("fileid",file.getName());
builder.addFormDataPart("teskid",CacheUtil.teskid);
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(CacheUtil.IP+"/File/saveFiles")
.header("Cookie", CacheUtil.Cookie)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Logs.i("onFailure: " + e);
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
Logs.i("成功" + response);
}
});
}
}
}
2 server端:
//保存图片到数据库中
@RequestMapping(value = "/saveFiles",method = RequestMethod.POST)
@ResponseBody
public Map saveFile(HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
System.out.println(file.getName());
if (!file.isEmpty()) {
try {
FileBean fileBean=new FileBean();
fileBean.setFfname(request.getParameter("specialname").toString());
System.out.println(request.getParameter("specialname").toString());
fileBean.setFfileid(request.getParameter("fileid").toString());
System.out.println(request.getParameter("fileid").toString());
fileBean.setTeskid(request.getParameter("teskid").toString());
fileService.save(fileBean, file.getInputStream());
map.put("resultcode", "200");
} catch (Exception e) {
e.printStackTrace();
stream = null;
map.put("resultcode", "100");
}
} else {
map.put("resultcode", "100");
}
}
return map;
}