学习笔记——SpringMVC文件上传与下载
2023-01-21
一、文件下载
1、实现文件下载步骤
(1)准备文件下载相关步骤
(2)将ResponseEntity<T>对象,作为方法返回值
(3)为ResponseEntity<T>对象,设置三个参数
2、示例代码
@RequestMapping("/fileDownloadController") public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename){ ResponseEntity<byte[]> responseEntity = null; try { //获取文件位置 //获取文件真实路径【(request|session)->ServletContext】 String realPath = request.getServletContext().getRealPath("/WEB-INF/download/" + filename); //输入流 InputStream is = new FileInputStream(realPath); //文件下载 byte[] bytes = new byte[is.available()]; is.read(bytes); //设置响应头 HttpHeaders headers = new HttpHeaders(); //设置要下载的文件的名字(及文件格式为附件格式,通知服务器下载当前资源,而不是打开) headers.add("Content-Disposition","attachment;filename"); //处理中文文件名问题 headers.setContentDispositionFormData("attachment",new String(filename)); //状态码 responseEntity = new ResponseEntity<>(bytes,headers, HttpStatus.OK); is.close(); } catch (Exception e) { e.printStackTrace(); } return responseEntity; }
二、文件上传
1、实现文件上传思路
(1)准备工作
①准备文件上传页面
表单的提交方式必须为POST
设置表单enctype属性值为multipart/form-data
表单中包含文件域(type=file)
②导入jar包
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
③装配解析器:CommonsMultipartResolver
<!-- 装配CommonsMultipartResolver--> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <!-- 设置字符集--> <property name="defaultEncoding" value="utf-8"></property> <!-- 设置总文件的大小--> <property name="maxUploadSize" value="102400"></property> </bean>
(2)实现步骤
①将type=file(文件域)直接入参:MultipartFile类型即可
②获取文件名称
@Controller public class FileUploadController { @RequestMapping("/fileUploadController") public String fileUploadController(String username, MultipartFile updateFile, HttpSession session){ try { //获取文件名称 String filename = updateFile.getOriginalFilename(); //获取上传路径 String realPath = session.getServletContext().getRealPath("/WEB-INF/upload"); //判断上传路径是否存在(如不存在,创建) File filePath = new File(realPath); if(!filePath.exists()){ filePath.mkdirs(); } //实现文件上传 //File.separator:是系统默认的分隔符 File uFile = new File(filePath+File.separator+filename); updateFile.transferTo(uFile); } catch (IOException e) { e.printStackTrace(); } return "success"; } }
三、文件上传优化
1、允许同名文件上传
(1)使用UUID解决文件名重复问题
UUID是一个32位16进制随机数(特点:唯一性)
//实现文件上传 //解决重复文件名上传的方式 String uuid = UUID.randomUUID().toString().replace("-", ""); //File.separator:是系统默认的分隔符 File uFile = new File(filePath+File.separator+uuid+filename);
(2)使用时间戳解决文件名重复问题
System.currentTimeMillis()
2、设置上传文件大小上限
在装配CommonsMultipartResolver时,设置上传文件的上限
<!-- 装配CommonsMultipartResolver--> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <!-- 设置字符集--> <property name="defaultEncoding" value="utf-8"></property> <!-- 设置总文件的大小--> <property name="maxUploadSize" value="102400"></property> </bean>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南