MVC文件上传与下载

文件上传

 导入依赖:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.2.2</version>
</dependency>
<!--文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--文件上传的字符集-->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!--文件上传的总大小-->
    <property name="maxUploadSize" value="5000000000"></property>
    <!--单个文件的大小-->
    <property name="maxUploadSizePerFile" value="5000000"></property>
</bean>
/*单文件上传*/
@RequestMapping("/fileUpload")
public String fileUpdate(MultipartFile upload ,HttpSession session) throws IOException {
    //获取绝对路径
    String realPath = session.getServletContext().getRealPath("/upload");
    //获取文件上传提交的文件名
    String filename = upload.getOriginalFilename();
    //组合路径+上传操作
    upload.transferTo(new File(realPath,filename));
    return "index";
}
/*多文件上传*/
@RequestMapping("/fileUploads")
public String fileUpdates(@RequestParam  MultipartFile[] upload ,HttpSession session) throws IOException {
    //获取绝对路径
    String realPath = session.getServletContext().getRealPath("/upload");
    for (MultipartFile item:upload){
        //获取文件上传提交的文件名
        String filename = item.getOriginalFilename();
        //组合路径+上传操作
        item.transferTo(new File(realPath,filename));
    }
    return "index";
}
/*文件下载*/
@RequestMapping("/download")
public ResponseEntity<byte[]> dowload(HttpSession session) throws Exception {
    //获取绝对路径
    String realPath = session.getServletContext().getRealPath("/upload");
    //组装路径转换为file对象
    File file=new File(realPath,"新建文本文档.txt");
    //设置头 控制浏览器下载对应文件
    HttpHeaders headers=new HttpHeaders();
    headers.setContentDispositionFormData("attachment",new String("新建文本文档.txt".getBytes("UTF-8"),"ISO-8859-1"));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

}
原文地址:https://www.cnblogs.com/XiaoyvYa/p/13361298.html