使用SpringMVC框架实现文件上传和下载功能

时间:2021-09-14 14:05:41

使用SpringMVC框架实现文件上传和下载功能

(一)单个文件上传

①配置文件上传解释器

<!—配置文件上传解释器 -->
<mvc:annotation-driven></mvc:annotation-driven>
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxInMemorySize" value="512000000" ></property>
<property name="maxUploadSize" value="20000000"></property>
</bean>

②在Controller层编写映射方法

@RequestMapping(value="upload")
public String upload(MultipartFile file) throws Exception{
File destfile = new File("D:/dir/" + file.getOriginalFilename());
file.transferTo(destfile);
return "/upload.jsp";
}

注意:spring MVC文件上传功能引用了commons-fileupload组件,实现文件上传功能需要引入commons-fileupload和commons-io包

(前端页面很简单,就是一个用来上传文件的input标签,但要注意标签的name属性要和映射方法的参数名对应,如“file”)

(二)多文件上传


@RequestMapping(value="upload")
public String upload(MultipartFile[] file) throws Exception{
for (MultipartFile file : files) {
File destfile = new File("D:/dir/" + file.getOriginalFilename());
file.transferTo(destfile);
}
return "/upload.jsp";
}

(三)文件下载


@RequestMapping(value="/{filename}/download")
public void download(@PathVariable String filename,HttpServletResponse response) throws Exception{
File file=new File("d:/dir/"+filename);
FileInputStream input = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes(),"ISO-8859-1"));
IOUtils.cope(input,out);
}

(注:文件下载需要修改应答头信息,将流以附件形式输出,并设置文件名的编码格式为ISO-8859-1)

———————————————————————————————————————————————————————————————————

The end   万有引力+

-

-

-

-

-

相关文章