10.springMVC中文件上传与下载

十.文件处理

1.文件上传

1-1 POM依赖
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>
1-2.配置文件
<!--
    文件上传
    SpringMVC帮我们使用fileupload进行了解析
    在它解析的过程中肯定会用到配置文件中bean的id
    在底层代码中,对该bean的id做了限制
    其id的值必须是multipartResolver
 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
</bean>
1-3.JSP
<form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"/><br/>
    文件:<input type="file" name="file"/><br/>
    <input type="submit" value="上传"/>
</form>
1-4.Controller

SpringMVC通过MultipartFile接口对文件上传进行了实现

其提供了一个实现类CommonsMultipartFile

想要实现文件上传,可以在方法的参数中直接使用CommonsMultipartFile作为参数

SpringMVC在读取请求的数据的时候,会自动对CommonsMultipartFile进行值的注入

由于CommonsMultipartFile是一个对象,对象默认不会自动添加@RequestParam注解

因此:必须在CommonsMultipartFile参数前主动添加@RequestParam(key)的注解

如果在使用文件上传的时候没有传递文件的数据,则由于@RequestParam(key)的原因,会报错

因为@RequestParam中的required属性默认值为true,表示必须有值

我们可以将其默认值改为false,设置为非必须即可

// 单文件上传
@RequestMapping("/upload")
public void upload(String username, @RequestParam(value = "file",required = false) CommonsMultipartFile file, HttpSession session) throws IOException {
    System.out.println("username:"+username);
    String cp = session.getServletContext().getRealPath("/upload");
    if(!file.isEmpty()){
        file.transferTo(new File(cp,file.getOriginalFilename()));
    }
}

// 多文件上传
@RequestMapping("/uploads")
public void uploads(String username, @RequestParam(value = "file",required = false) CommonsMultipartFile[] files, HttpSession session) throws IOException {
    System.out.println("username:"+username);
    String cp = session.getServletContext().getRealPath("/upload");
    for(CommonsMultipartFile file : files) {
        if (!file.isEmpty()) {
            file.transferTo(new File(cp, file.getOriginalFilename()));
        }
    }
}

2.文件下载

使用ResponseEntity实现

@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
    String cp = session.getServletContext().getRealPath("/resource/jstl.jar");
    File file = new File(cp);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment","jstl.jar");
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值