SpringMVC实现文件的上传下载

Posted GaoYang-笔迹

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC实现文件的上传下载相关的知识,希望对你有一定的参考价值。

SpringMVC文件上传下载

1. 步骤分析

  • 创建好工程并配置好SpringMVC基本环境,并引入上传文件需要的两个包:commons-fileupload-1.3.1.jar和commons-io-2.4.jar。
  • 创建上传页面upload.jsp
  • 在Spring的核心配置文件中注册上传处理器
  • 编写Controller层,从页面获取到然后存入指定的文件夹
  • 编写下载和显示界面show.jsp
  • 实现controller层下载功能

2. 代码实现

2.1、导入jar包

 <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
 </dependency>
 <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
 </dependency>

2.2、创建upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片上传下载</title>
    <style>
        #box
            width: 600px;
            height: 600px;
            margin: 100px auto;
        
    </style>
</head>
<body>
<div id="box">
    <form action="/springmvc/oss.do" method="post" enctype="multipart/form-data">
       选择文件:<input type="file" name="img"/><br/>
        <input type="submit" value="提交">
    </form>
</div>
</body>
</html>

2.3、在SpringMVC核心配置文件注册上传处理器

    <mvc:resources mapping="/upload/**" location="/upload/"></mvc:resources>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 设置上传文件的大小上限,单位:byte10m=1024k 1k=1024b -->
        <property name="maxUploadSize" value="10240000"/>
    </bean>

2.4、编写Controller层

@RequestMapping("/upload.do")
    public ModelAndView upload(MultipartFile file, HttpServletRequest req) throws IOException 
        // 获得原始文件名称
        String originalFileName = file.getOriginalFilename();
        String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 生成新文件名
        String newFlieName = UUID.randomUUID().toString() +suffixName;
        // 保存到指定的文件路径
        String uploadDir = req.getServletContext().getRealPath("/upload");
        File f = new File(uploadDir);
        if(!f.exists())
            f.mkdir();
      	
      	file.transferTo(new File(uploadDir,newFlieName));
        System.out.println("文件上传到服务器的位置:" + uploadDir + "/" + newFlieName);
        ModelAndView mv = new ModelAndView();
        mv.addObject("newFlieName",newFlieName);
        mv.addObject("originalFileName",originalFileName);
        mv.setViewName("show");
        return mv;
    

2.5、编写下载和显示界面show.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图片上传下载</title>
</head>
<body>
<div>$originalFileName上传成功!</div>
<img src="<%=request.getContextPath() %>/upload/$newFlieName" style="width:300px; height: 200px;">
<a href="<%=request.getContextPath() %>/download.do?newImgName=$newFlieName&originalFileName=$originalFileName">下载</a>
</body>
</html>

2.6、实现controller层下载功能

@RequestMapping("/download.do")
    public ResponseEntity<byte[]> download(HttpServletRequest request,String newImgName,String originalFileName) throws IOException 
        // 获取文件所在文件夹路径
        String path = request.getServletContext().getRealPath("/upload/")+newImgName;
        // 读取图片
        byte[] imgbody = FileUtils.readFileToByteArray(new File(path));
        // 防止下载乱码
        String downloadImgName = new String(originalFileName.getBytes("UTF-8"), "iso-8859-1");
        // 设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",downloadImgName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(imgbody, httpHeaders, HttpStatus.OK);
        return responseEntity;
 

3. 运行测试

以上是关于SpringMVC实现文件的上传下载的主要内容,如果未能解决你的问题,请参考以下文章

如何使用springmvc实现文件上传

springmvc怎么将上传本地文件到文件服务器

SpringMVC实现文件的上传下载

SpringMvc文件上传

SpringMVC实现文件上传

springMVC实现 MultipartFile 多文件上传,StandardMultipartHttpServletRequest上传文件,在请求中上传文件,比如上传图片