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

使用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   万有引力+

 

-

 

-

 

-

 

-

 

-

 

转载于:https://www.cnblogs.com/wyyl-/p/10734122.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值