文件上传可以说开发人员的基本技能
SpringBoot项目结构与ssm有很大区别,文件上传也有差异
- 页面
<!DOCTYPE html>
<html>
<head>
<title>文件上传示例</title>
</head>
<body>
<h2>文件上传示例</h2>
<hr/>
<form method="POST" enctype="multipart/form-data" action="/recruit/upload">
<p>
文件:<input type="file" name="img" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</body>
</html>
- 后台文件上传处理
文件上传一般在Controller实现
FileUploadController文件
//spring boot 实现上传图片
@PostMapping("upload")
@ResponseBody
public String upload(@RequestParam("img") MultipartFile img, HttpServletResponse response) throws IOException {
String result=null;
response.setHeader("content-type","text/html;charset=UTF-8");
if (!img.isEmpty()) {
// 获取文件名
String fileName = img.getOriginalFilename();
//生成随机文件名
String name =UUID.randomUUID().toString().replaceAll("-", "");
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("上传的文件后缀名为:" + suffixName);
//判断文件的类型是否为指定的文件类型
if (!filterType(img.getContentType())) {
result = "error:" + img.getContentType()+ " type not upload file type";
}else {
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("D://upload/" + name+suffixName)));
out.write(img.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
result = "upload file failed !";
} catch (IOException e) {
e.printStackTrace();
result = "upload file failed !";
}
result = "upload file success !";
}
}else{
result="upload file failed !";
}
return result;
}
/**
* 指定的上传类型 zip 和 图片格式的文件
*/
private static final String[] types = { "application/x-zip-compressed",
"ZIP", "image/pjpeg","image/x-png","image/jpeg","image/jpg" ,"image/JPG","image/png","image/PNG"}; //"application/octet-stream; charset=utf-8",
/***
* 判断文件的类型是否为指定的文件类型
* @return
*/
public boolean filterType(String imgType) {
boolean isFileType = false;
for (String type : types) {
if (type.equals(imgType)) {
isFileType = true;
break;
}
}
return isFileType;
}
- 配置Bean来设置文件大小
@Configuration
public class FileUploadConfiguration {
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory =new MultipartConfigFactory();
//文件大小
factory.setMaxFileSize("2MB");
//文件存放临时文件夹
factory.setLocation("C://TEMP/");
return factory.createMultipartConfig();
}
}
运行结果:成功!