控制器UploadController 实现
UploadController 主要分为3部分
1.1 调整页面请求goUploadImg
1.2 上传请求方法uploadImg
1.3 存储图片方法uploadFile
@Controllerpublic class UploadController {
//跳转到上传文件的页面
@RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {
//跳转到 templates 目录下的 uploadimg.html
return "uploadimg";
}
//处理文件上传
@ResponseBody //返回json数据
@RequestMapping(value = "/testUploadimg", method = RequestMethod.POST)
public String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
tring contentType = file.getContentType();
String fileName = file.getOriginalFilename();
String filePath = "D:/img";
if (file.isEmpty()) {
return "文件为空!";
}
try {
uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
//返回json
return "上传成功";
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
out.write(file);
out.flush();
out.close();
}
}
2:同时需要将上传图片的原始文件名和存储文件名、以及关联id存入一个数据表中。
2.1 将存储文件名设置为UUID,避免存储文件名重复
public static String getUUID(){
UUID uuid=UUID.randomUUID();
String str = uuid.toString();
String uuidStr=str.replace("-", "");
return uuidStr;
}
2.2 将存储文件名按照时间生成,避免存储文件名重复
System.nanoTime()
该函数是返回纳秒的。1毫秒=1纳秒*1000*1000
如:long time1=System.nanoTime();
2.3 或者借助于SimpleDateFormat 将Date格式化到毫秒也可以解决文件重名的问题。