boot项目中上传&下载
<!-- pom依赖 上传下载-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@PostMapping("/insertData")
public ResultMap insertData(PortalNews portalNews, MultipartFile file) {
if (file == null) {
industryInfoService.insertData(portalNews);
return new ResultMap(200);
} else if (file.getSize() > (8 * 1024 * 1024)) {
return new ResultMap().error("文件过大");
} else {
BASE64Encoder base64Encoder = new BASE64Encoder();
byte[] bytes = new byte[0];
try {
bytes = file.getBytes();
String encode = base64Encoder.encode(bytes);
portalNews.setNewsImageUrl(encode);
} catch (IOException e) {
e.printStackTrace();
}
industryInfoService.insertData(portalNews);
return new ResultMap(200);
}
}
@GetMapping("/download")
public void downloadFileAction(HttpServletRequest request, HttpServletResponse response, int idd) throws IOException {
response.setCharacterEncoding(request.getCharacterEncoding());
BannerDesc ll = portalNewsService.find(idd);
String newsImageUrl = ll.getBannerImageUrl();
String bannerDesc1 = ll.getBannerDesc();
String bannerDesc = ll.getButtonUrl2();
String fileName =bannerDesc1+bannerDesc;
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] bytes = base64Decoder.decodeBuffer(newsImageUrl);
response.setContentType("application/multipart/form-data");
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
OutputStream os = response.getOutputStream();
os.write(bytes);
os.close();
}