前端代码
<body>
<h1>实现文件上传</h1>
<!--enctype="开启多媒体标签" -->
<form action="http://localhost:8091/file" method="post"
enctype="multipart/form-data">
<input name="file" type="file" />
<input type="submit" value="上传"/>
</form>
</body>
后端代码
@Controller
public class FileController {
/**
* @param file
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping("/file")
@ResponseBody
public String file(MultipartFile file) throws IllegalStateException, IOException {
//获取文件名称
String fileName = fileImage.getOriginalFilename();
//校验图片类型
if(!fileName.matches("^.+\\.(jpg|png|gif|JPG|PNG|GIF)$")) {
return "0";
}
//判断是否为恶意程序
try {
BufferedImage bufferedImage =
ImageIO.read(file.getInputStream());
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(width==0 || height ==0) {
return "0";
}
//准备文件夹
String dateDir =
new SimpleDateFormat("yyyy/MM/dd")
.format(new Date());
String localDir = localDirPath + dateDir;
File dirFile = new File(localDir);
if(!dirFile.exists()) {
//如果文件不存在,则创建文件夹
dirFile.mkdirs();
}
//使用UUID定义文件名称
String uuid =
UUID.randomUUID().toString().replace("-","");
//图片类型
String fileType =
fileName.substring(fileName.lastIndexOf("."));
//拼接新的文件名称
String realLocalPath = localDir+"/"+uuid+fileType;
//完成文件上传
uploadFile.transferTo(new File(realLocalPath));
//todo 可把图片信息存入数据库
} catch (Exception e) {
e.printStackTrace();
return "0";
}
return "1";
}
}