- 在一创建好的项目中导入文件上传的jar包,commons-fileupload , Maven会自动帮我们导入他的依赖包 commons-io包。
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
- 在springmvc配置文件中添加以下配置
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) 若设置为-1则不限制大小-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
- 编写前端页面:form表单设置属性enctype=“multipart/form-data”,若要限制可上传文件的类型,可accept属性限制,这里将其设置为accept=“image/*”(可上传所有格式的图片)。
上传:
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" accept="image/*" name="file"/>
<input type="submit" value="upload">
</form>
下载:
<form action="/download" method="get">
<input type="submit" value="下载">
</form>
- controller层相应代码
//上传
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request
) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
String filename=null;
if(!file.isEmpty()){
fileName=file.getOriginalFilename();
//防止文件名重复,设置随机文件名
//获取文件后缀
String fileSuffix = fileName.substring(filename.lastIndexOf("."));
File path = new File(path );
if (!path.exists()){
//mkdirs()可创建多级目录
path.mkdirs();
}
String lastFileName=UUID.randomUUID().toString().replaceAll("-","")+fileSuffix;
file.transferTo(new File(path,lastFileName)) ;
}
return "redirect:/index.jsp";
}
//下载
@RequestMapping(value="/download")
public void downloads(HttpServletResponse response ,HttpServletRequest request
) throws Exception{
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
//要下载的文件名,这里可和数据库结合使用
String fileName = "基础语法.jpg";
//1、设置response 响应头response.reset();
//设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
fileName = URLEncoder.encode(fileName,"UTF-8");
//设置响应头
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
//BufferedInputStream本身带有缓存,所以受data数组的大小影响较小
//2、读取文件——输入流
InputStream in= new BufferedInputStream(new FileInputStream(new File(path,fileName)));
//3、写出文件——输出流
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
//每次的搬运量
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
//5、关闭流(先打开的后关闭)
out.close();
in.close();
}
OK!