多张图片上传功能java后端代码实现,并返回访问的图片的url

时间:2024-02-22 16:31:28

1.controller代码

/**
* 图片上传功能
*
* @param multipartFile //图片文件
* @param missionId
* @return
*/
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
public ResponseEntity<Map<String, Object>> imageUploa(@RequestParam("multipartFile") MultipartFile[] multipartFile,
@RequestParam("missionId") String missionId, HttpServletRequest request) {
Map<String, Object> message = Maps.newHashMap();
//照片路径info
String info = "";
//照片路径列表list
ArrayList<String> list = new ArrayList<>();
for (MultipartFile file : multipartFile) {
info = missionService.uploadPictureByFile(missionId, file);
list.add(info);
}
if (list.size() > 0) {
//图片上传成功
message.put("data", list);
message.put(Constant.RETURNCODE_KEY_OPTRESULT, Constant.AUTH_SUCCESS);
return ResponseEntity.ok(message);
}
//图片上传失败
message.put(Constant.RETURNCODE_KEY_OPTRESULT, Constant.INVALID_PARAM);
return new ResponseEntity<Map<String, Object>>(
message,
HttpStatus.BAD_REQUEST);
}



2.service代码

/**
* 图片上传方法,并把图片访问路径保存到数据库
*
* @param missionId
* @param file
* @return //返回上传成功的url
*/
/**
* 图片上传到服务器的保存路径
*/
public static final String PICTUREURL = Global.getConfig("PICTUREURL");//配置在配置文件中

/**
* 图片上传的服务器和二维码生的服务器
*/
public static final String CONFIGUREURL = Global.getConfig("CONFIGUREURL");//配置在配置文件中


@Transactional(readOnly = false, rollbackFor = Exception.class)
public String uploadPictureByFile(String missionId, MultipartFile file) {
String filename1 = "picture_" + UUID.randomUUID() + ".jpg";//生成唯一图片路径
if (!file.isEmpty()) {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//设置允许上传文件类型
String suffixList = "jpg,png,ico,bmp,jpeg";
if (suffixList.contains(suffix)) {
try {
File filepath = new File(PICTUREURL);
if (!filepath.exists()) {
filepath.mkdirs();
}
// 文件保存路径
String savePath = PICTUREURL + filename1;
// 转存文件
file.transferTo(new File(savePath));
String url = CONFIGUREURL + filename1;
missionDao.saveMissionPic(missionId, url,new Date()); //本项目用于保存图片的url的数据库插入数据
return url;
} catch (Exception e) {
e.printStackTrace();
return String.valueOf(e);
}
} else {
return "上传的文件不是图片";
}

} else {
return "请选择图片上传";
}
}