springmvc 文件上传与下载
程序员文章站
2022-06-02 14:38:06
...
springmvc上传与下载
必须导入jar包
如果是maven项目导入依赖包
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
在spring的servlet视图解析器下面定义CommonsMultipartResolver文件解析器,就是加入这个的时候运行项目,如果没有fileuload相关的jar包就会报错。
在spring mvc 的配置文件中书写xml配置
<!-- 定义文件解释器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 上传图片最大大小5M-->
<property name="maxUploadSize" value="5242440"></property>
</bean>
代码演示
@RequestMapping("file")
@Controller
public class FileController {
/**
* 文件上传功能
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File dir = new File(path,fileName);
if(!dir.exists()){
dir.mkdirs();
}
//MultipartFile自带的解析方法
file.transferTo(dir);
return "ok!";
}
/**
* 文件下载功能
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/down")
public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{
//模拟文件,myfile.txt为需要下载的文件
String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt";
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//假如以中文名下载的话
String filename = "下载文件.txt";
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
}
}
from表单提交时一定要设置文件上传属性
上传时的文件名name 一定要与方法中的形参一致
enctype="multipart/form-data"
<form action="http://localhost:8080/uploadDemo/rest/file/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="上传">
</form>
<form action="http://localhost:8080/uploadDemo/rest/file/down" method="get">
<input type="submit" value="下载">
</form>