文件上传与下载
一、文件上传:
文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
测试页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form action="/fileUpload" method="post" enctype="multipart/form-data"> <!--<input type="hidden" name="_method" value="post"> --> 图片:<input type="file" name="file"> <br /> <input type="submit" name="上传"> </form> </body> </html>
控制层:
package com.cy.store.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; @RestController public class FileUploadController { @RequestMapping("/fileUpload") public String upload(MultipartFile file) { File dir=new File("fileUpload");//当前项目下路径 if(!dir.exists()) { dir.mkdir();//创建目录 } System.out.println(dir.getAbsolutePath());//绝对路径 String originalFilename = file.getOriginalFilename();//文件初始名称 String hzname = originalFilename.substring(originalFilename.lastIndexOf("."));//后缀 .jpeg String uuid = UUID.randomUUID().toString();//UUID 通用唯一识别码 String fileName=uuid+hzname; //最后生成的文件名 / 防重命名直接覆盖 String finalPath=dir.getAbsolutePath()+File.separator+fileName;//上传的文件最后存储的绝对路径 try { file.transferTo(new File(finalPath)); //将上传的文件中的数据写入到新创建的文件中 } catch (IOException e) { e.printStackTrace(); } return "上传成功!"; } }
文件所在位置:
二、文件下载
ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
使用ResponseEntity实现下载文件的功能
测试页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件下载</title> </head> <body> <a href="/fileDownload?fileName=11.jpg">下载测试</a> </body> </html>
注意:可以在配置文件中配置文件所在的目录路径:
引用时用 @Value("${file.realpath}") 作用在指定变量上,为变量赋值。
控制层:
package com.liang.manager_system.controller.file; import com.liang.manager_system.util.JsonResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @RestController public class FileDownloadController { @Value("${file.realpath}") String path; @RequestMapping("/fileDownload") public ResponseEntity<byte[]> fileDownload(@RequestParam("fileName") String fileName, HttpSession session) throws Exception { // String realPath = session.getServletContext().getRealPath("/"); // System.out.println(realPath); 每次重新部署,地址都不一样 String name=fileName; //创建输入流 InputStream is = new FileInputStream(path+"/fileUpload/"+name); //创建字节数组 byte[] bytes = new byte[is.available()]; //将流读到字节数组中 is.read(bytes); //创建HttpHeaders对象设置响应头信息 MultiValueMap<String, String> headers = new HttpHeaders(); //设置要下载方式以及下载文件的名字 headers.add("Content-Disposition", "attachment;filename="+name); //设置响应状态码 HttpStatus statusCode = HttpStatus.OK; //创建ResponseEntity对象 ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode); //关闭输入流 is.close(); return responseEntity; } }
三、得到文件列表
控制层:
package com.liang.manager_system.controller.file; import com.liang.manager_system.controller.BaseController; import com.liang.manager_system.pojo.FileClass; import com.liang.manager_system.util.JsonResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @RestController public class FileListController extends BaseController { public static String getPrintSize(long size) { // 如果字节数少于1024,则直接以B为单位,否则先除于1024,后3位因太少无意义 double value = (double) size; if (value < 1024) { return String.valueOf(value) + "B"; } else { value = new BigDecimal(value / 1024).setScale(2, BigDecimal.ROUND_DOWN).doubleValue(); } // 如果原字节数除于1024之后,少于1024,则可以直接以KB作为单位 // 因为还没有到达要使用另一个单位的时候 // 接下去以此类推 if (value < 1024) { return String.valueOf(value) + "KB"; } else { value = new BigDecimal(value / 1024).setScale(2, BigDecimal.ROUND_DOWN).doubleValue(); } if (value < 1024) { return String.valueOf(value) + "MB"; } else { // 否则如果要以GB为单位的,先除于1024再作同样的处理 value = new BigDecimal(value / 1024).setScale(2, BigDecimal.ROUND_DOWN).doubleValue(); return String.valueOf(value) + "GB"; } } @Value("${file.realpath}") String path; @GetMapping("/fileList") public JsonResult<List<FileClass>> getFileList(Model model) { File dir=new File(path+"/fileUpload"); File[] files = dir.listFiles(); List<FileClass> fileLists = new ArrayList<FileClass>(); for(File f:files){ long l = f.length(); String fileSize = getPrintSize(l); FileClass file = new FileClass(); file.setFileName(f.getName()); file.setFilePath(f.getAbsolutePath()); file.setFileSize(fileSize); fileLists.add(file); } model.addAttribute("fileLists",fileLists); return new JsonResult<>(OK,fileLists); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!