Activity代码
btn_register_info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url=ServiceUrls.getReserveMethodUrl("picture");
Map<String,Object> map=new HashMap<>();
map.put("picturename", picturename);//图片名称
Map<String, File> fileMap = new HashMap<>();
//file 从图库返回的图片
//files 从拍照返回的图片
if (file!=null){
fileMap.put("photo", file);
}else if (files!=null){
fileMap.put("photo", files);
}else {
Toast.makeText(mActivityContext,"请选择图片",Toast.LENGTH_LONG).show();
}
//显示加载层
loadingDialog.setLoadingText("上传中...").show();
OkHttpTool.httpPostWithFile(url, map, fileMap, new OkHttpTool.ResponseCallback() {
@Override
public void onResponse(boolean isSuccess, int responseCode, String response, Exception exception) {
mActivityContext.runOnUiThread(new Runnable() {
@Override
public void run() {
//关闭加载层
loadingDialog.close();
String strText = "网络环境不佳,请稍后再试";
if (isSuccess && responseCode == 200) {
try {
JSONObject jsonObject = new JSONObject(response);
int code = jsonObject.getInt("code");
strText = jsonObject.getString("text");
if (code == 200) {
Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
}else {
Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(mActivityContext, "上传失败", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
}
});
}
});
}
});
服务端代码
@ResponseBody
@RequestMapping(value = "/picture", produces = "application/json;charset=UTF-8")
public Object picture (@RequestParam(value = "photo") MultipartFile mPhoto,String picturename) {
JsonReturn jsonReturn = new JsonReturn();
// 判断文件是否为空
if (!mPhoto.isEmpty() && mPhoto.getSize() > 0) {
// 判断memberId
// 获取文件名称
String fileName = mPhoto.getOriginalFilename();
// 获取文件扩展名称
String strExt = fileName.substring(fileName.lastIndexOf('.'));
String picturenames = picturename + strExt;
// 保存图片
FileUtils.writeByteArrayToFile(new File(AppSeting.UPLOAD_PRODUCT_DIR, picturenames),mPhoto.getBytes()); //图片没有放到数据库里面,而是放在了其他地方
} else {
jsonReturn.setCode(500);
jsonReturn.setText("上传的图片为空");
}
return gson.toJson(jsonReturn);
}