- 页面
<form method="post" action="/DuoFile" enctype="multipart/form-data">
<div class="form-group">
<div class="label">
<label>图片:</label>
</div>
<div class="field">
<input type="text" th:value="1" name="lib_id" hidden="hidden"/>
<input type="file" name="img" class="input" value="" required/>
</div>
</div>
</form>
- 控制器
@RequestMapping("/DuoFile")
@ResponseBody
public String dataPicAdd(@RequestParam(value = "submit",required = false) String submit,
@RequestParam(value = "img",required = false) List<MultipartFile> uploadImage,
Model model) throws Exception{
System.out.println("DuoFile:");
String facePath = null;
if (submit!=null) {
System.out.println("图片数量:"+uploadImage.size());
JSONObject json = new JSONObject();
if (uploadImage == null) {
return "上传失败,上传图片数据为空";
} else {
for (int i=0;i<uploadImage.size();i++){
String suffix = uploadImage.get(i).getContentType().toLowerCase();//图片后缀,用以识别哪种格式数据
suffix = suffix.substring(suffix.lastIndexOf("/") + 1);
if (suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("png") || suffix.equals("gif")) {
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
//保存路径
String imgFilePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/images";
File targetFile = new File(imgFilePath, fileName);
if (!targetFile.getParentFile().exists()) { //判断父级路径是否存在
targetFile.getParentFile().mkdirs();//创建目录
}
//保存
uploadImage.get(i).transferTo(targetFile);
String sTestsetFile = facePath;
return"上传图片成功";
} else {
return "上传图片格式非法";
}
}
}
}
}
- maven
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
小白一枚,遇到问题,欢迎评论