qiuxuhui

导航

Spring mvc 实现文件上传与下载

一:实现文件上传并能前端显示的功能

  导入包

  

<!--    文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

  

  修改spring-web.xml,配置文件上传解析器和静态资源映射

<!-- 4、文件上传解析器-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>

    <!--    5、静态资源映射
            mapping : 客户端浏览器路径  images/1.jpg   images/product/2.jpg
            location: 项目根据路径的下的指定目录下   /WEB-INF/images/1.jpg  /WEB-INF/images/2.jpg
    -->
    <mvc:resources mapping="/images/**" location="/WEB-INF/images/"></mvc:resources>

  在WEB-INF中新建一个images文件夹,最好在里面新建一个文件

 

 

   创建Controller测试

package com.cc.mvc.web;

import com.cc.mvc.response.ServerResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {


    @RequestMapping("/add")
    public String addUpload(){
        return "add";
    }

    /**
     * 文件上传
     * @param uploaderUser
     * @param uploadFile
     * @return
     * 注意:
     * 1.默认情况下上传的参数名必须和表单元素的name属性值一致,文件上传表单的name属性值
     * 必须和文件上传方法的MultipartFile参数名一致。
     *
     * 2、文件上传导入依赖(uploadfile)和配置文件上传解析器
     *
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ServerResponse upload(HttpServletRequest request,String uploaderUser, MultipartFile uploadFile) throws IOException {
        //1.获取上传文件的原始名称
        String originFileName = uploadFile.getOriginalFilename();
        System.out.println("====upload===>originFileName:"+originFileName);
        //2.随机生成一个文件名  随机名+文件后缀
        String newFileName = UUID.randomUUID().toString()+originFileName.substring(originFileName.lastIndexOf("."));
        //3.文件存储到tomcat服务器的webapps的项目的工程 upload文件夹下
        //3.1 动态获取tomcat服务器的路径
        String rootPath = request.getServletContext().getRealPath("/WEB-INF")+"/images/";

        File file =new File(rootPath,newFileName);
        //将文件保存到磁盘:
        uploadFile.transferTo(file);
        return ServerResponse.ok(null);
    }

}

  

  编写上传文件jsp

<%--
  Created by IntelliJ IDEA.
  User: mr.chan
  Date: 2020-12-25
  Time: 16:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
    <title>文件上传与下载</title>
</head>
<body>
<%--文件上传:
1、表单必须为 post提交方式
2、表单的编码类型改为:multipart/form-data
3、必须使用文件域

encoding  type==>encttype
--%>
<form action="upload" method="post" enctype="multipart/form-data">
    上传人姓名:<input type="text" name="uploaderUser"/><br/>
    身份证:<input type="file" name="uploadFile"/><br/>
    <input type="submit" value="上传"/>
</form>


<img src="${pageContext.request.contextPath}/images/2e856afb-b715-446b-9541-35fe25cfb7cf.png">

</body>
</html>

  

 

 

 

 

 

 

 

 

 

二,下载

  在Controller中加入测试方法

  

@RequestMapping("/filesdownloads")
    public ResponseEntity<byte[]> EIToolDownloads(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String doenLoadPath =request.getServletContext().getRealPath("/WEB-INF")+"/images/"; // doenLoadPath是文件路径(一般指服务器上的磁盘位置)
File file = new File(doenLoadPath); if(file.exists()){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
headers.setContentDispositionFormData("attachment", file.getName());
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}else{ System.out.println("文件不存在,请重试...");
return null; }
}

  JSP页面中写入一个<a>标签

  

<a href="/filesdownloads" >下载</a>
 
  或者:点击button触发下载功能
  
<button onclick="download()"></button>

function download(){
               self.location.href("/filesdownloads");
              
        }

posted on 2020-12-26 14:52  qiuxuhui  阅读(124)  评论(0编辑  收藏  举报