附件上传
1.上传图片附件并使用BufferedImage进行处理
@PostMapping(value = "uploadImg/{type1}/{type2}")
@SYS_LOG(module = "用户", type = "新增", description = "上传文件")
@ResponseBody
public String uploadImg(@RequestParam("files") CommonsMultipartFile[] files,
@PathVariable("type1") String type1 ,@PathVariable("type2") String type2) throws IOException {
Date date = new Date();
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
String dateStr = sd.format(date);
String bigPath = "C:\\systemImg\\uploadImg\\big\\"+ type1+"\\"+type2+"\\"+dateStr ;// 大图片路径
String smallPath = "C:\\systemImg\\uploadImg\\small\\"+ type1+"\\"+type2+"\\" + dateStr ;// 小图片路径
String returnPath = ""; // 返回值
try {
File dirb = new File(bigPath);
if (!dirb.exists()) {
dirb.mkdirs();
}
File dirs = new File(smallPath);
if (!dirs.exists()) {
dirs.mkdirs();
}
if (files.length > 0 && files != null) {
for (int i = 0; i < files.length; i++) {
Random random = new Random();
int randomNo = random.nextInt(10000);
CommonsMultipartFile file = files[i];
BufferedImage img = ImageIO.read(file.getInputStream());
if (img == null) {
continue;
} else {
bigPath = "C:\\systemImg\\uploadImg\\big\\"+ type1+"\\"+type2+"\\"+dateStr ;// 大图片路径
smallPath = "C:\\systemImg\\uploadImg\\small\\"+ type1+"\\"+type2+"\\" + dateStr ;// 小图片路径
bigPath += "\\"+ randomNo + "_" + file.getOriginalFilename();
smallPath += "\\" + randomNo + "_" + file.getOriginalFilename();
File localBigFile = new File(bigPath);
//File localSmallFile = new File(smallPath);
BufferedImage buffImg = null;
buffImg = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB);
files[i].transferTo(localBigFile);
buffImg.getGraphics().drawImage(
img.getScaledInstance(300, 200, img.SCALE_SMOOTH), 0,
0, null);
String name=files[i].getFileItem().getName();
String type=name.substring(name.lastIndexOf(".")+1 );
ImageIO.write(buffImg, type, new File(smallPath));
returnPath += dateStr + "/" + randomNo + "_" + file.getOriginalFilename() + ",";
}
}
}
return dateStr + "/" + returnPath.substring(0, returnPath.length() - 1);
}catch (IllegalStateException | IOException e) {
e.printStackTrace();
return "error";
}
}
注:type 1,type2为文件夹名
2.spring-mvc配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="10240"/>
</bean>
3.jar依赖
spring-context-4.3.14.RELEASE

浙公网安备 33010602011771号