我使用了hutool的 FileUtil,IdUtil,所以需要引入hutool:
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.11</version> </dependency>
application.yml 中定义上传文件目录:
files: upload: path: D:/java_workspace/springboot_demo/upload/
上传页面:
<form action="/files/upload" method="post" enctype="multipart/form-data"> <div><input type="file" name="file"></div> <div><input type="submit" value="上传"></div> </form>
上传下载处理:
package com.example.demo.controller; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; @RestController @ResponseBody @RequestMapping(value ="/files") public class Files { @Value("${files.upload.path}") private String fileUploadPath; //上传 @PostMapping(value ="/upload") public String upload(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { String originalFilename = file.getOriginalFilename(); //文件名.jpg String type = FileUtil.extName(originalFilename);//.jpg long size = file.getSize();//大小 String uuid = IdUtil.fastSimpleUUID(); String filename = uuid + "." + type; File uploadFile = new File(fileUploadPath +"/"+ filename); //先存储到磁盘 if (!uploadFile.getParentFile().exists()) { uploadFile.getParentFile().mkdirs(); } file.transferTo(uploadFile); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html;charset=utf-8"); response.setContentType("text/html;charset=utf-8"); String str = ""; str += "<html lang=\"zh-CN\">\n"; str += "<head>\n"; str += "<meta charset=\"utf-8\">\n"; str += "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\n"; str += "</head>\n"; str += "<body>\n"; str += "file: "+originalFilename+" upload success, <br /><a href='/files/download/"+filename+"' target" + "='_blank'>download" + "</a" + ">\n"; str += "</body>\n"; str += "</html>\n"; return str; } //下载 @GetMapping("/download/{filename}") public void download(@PathVariable String filename, HttpServletResponse response) throws IOException { File uploadFile = new File(fileUploadPath +"/"+ filename); ServletOutputStream os = response.getOutputStream(); response.addHeader("Contene-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8")); response.setContentType("application/octet-stream"); os.write(FileUtil.readBytes(uploadFile)); os.flush(); os.close(); } }
效果:
标签:丝滑,springboot,上传下载,upload,filename,str,import,response,String From: https://www.cnblogs.com/xuxiaobo/p/17061859.html