1.文件上传
1.1 pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
1.2.springmvc.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
1.3.controller层
@RequestMapping("upload")
public String uploadFile(HttpServletRequest request){
MultipartHttpServletRequest mhs=(MultipartHttpServletRequest) request;
MultipartFile mf=mhs.getFile("file");
try{
if(mf != null && mf.getSize() > 0){
String basePath=request.getSession().getServletContext().getRealPath("/");
File upload = new File(basePath + "/upload");
if(!upload.exists()){
upload.mkdir();
}
String fileName=System.currentTimeMillis() +
mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
mf.transferTo(new File(upload,fileName));
request.setAttribute("msg","success upload");
}
}catch (Exception e){
e.printStackTrace();
request.setAttribute("msg","failure upload");
}
return "result";
}
public void file(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception{
String fileName = file.getOriginalFilename();
File desFile = new File(request.getServletContext().getRealPath("/"),fileName);
file.transferTo(desFile);
response.getWriter().print(desFile.getAbsolutePath());
}
1.4.file.jsp
<form action="fileUp" method="post" enctype="multipart/form-data">
<input type="file" name="file"> <br>
<button type="submit"> submit </button>
</form>
2.文件下载
2.1 cobtroller
@RequestMapping("/fileDown")
public void file(HttpServletRequest request, HttpServletResponse response) throws Exception{
File file = new File(request.getServletContext().getRealPath("/"), "lwx.docx");
byte[] data = FileUtils.readFileToByteArray(file);
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment;filename="
+ new String(file.getName().getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.getOutputStream().write(data);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!