首页 > Web开发 > 详细

mvc文件上传和下载

时间:2019-11-11 13:51:55      阅读:79      评论:0      收藏:0      [点我收藏+]

文件上传

  导入依赖:

技术分享图片
<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>
View Code

  spring-mvc文件配置:  

技术分享图片
<!--文件上传解析器-->
<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>
View Code

  控制器(单文件)

技术分享图片
/*单文件上传*/
@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";
}
View Code

  控制器(多文件)

技术分享图片
/*多文件上传*/
@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";
}
View Code

文件下载

技术分享图片
/*文件下载*/
@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);

}
View Code

 

mvc文件上传和下载

原文:https://www.cnblogs.com/wnwn/p/11834328.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!