springmvc上传下载文件

1. 概述

本篇博客基于《springmvc注解项目开发流程》的代码,实现web前端的文件上传和下载功能。

主要参考包括:《SpringMVC学习(二)——快速搭建SpringMVC开发环境(注解方式)》

该博客源码托管地址:https://gitee.com/leo825/spring-framework-learning-example

2. 环境配置

2.1 pom.xml添加依赖

修改pom.xml里,添加上传文件依赖

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

2.2 liwl-springmvc-servlet.xml配置bean

修改liwl-springmvc-servlet.xml修改

<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"></property>
    <property name="maxUploadSize" value="104857600"></property>
</bean>

3.文件上传

3.1 创建前端页面

创建一个前端jsp用于接受上传文件请求。在WEB-INF/views/目录下创建uploadpage.jsp,内容如下

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>

<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file" value="请选择需要上传的文件" /><br>
    <input type="submit" value="提交">
</form>

</body>
</html>

创建上传成功后显示的页面uploadsuccess.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<p>
    上传成功
</p>
</body>
</html>

3.2 创建后端代码

在controller目录下创建FileUploadController.java

package com.liwl.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

    @RequestMapping(value = "/fileupload",method = RequestMethod.GET)
    public ModelAndView liwanliang() throws ServletException,IOException{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("uploadpage");
        return modelAndView;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam(value = "file") MultipartFile multipartFile,HttpServletRequest request) throws IOException{
        if (!multipartFile.isEmpty()){
            String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
            String fileName = multipartFile.getOriginalFilename();
            File fileDir = new File(fileDirStr);
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
            File filetmp = new File(fileDir, fileName);
            multipartFile.transferTo(filetmp);
        }

        return "uploadsucces";
    }
}

前端代码通过post请求,向/upload的URL发送了上传file的请求

后端接收该请求,创建/uploadFile目录,把文件放置在该目录下,并返回uploadsuccess的页面

访问:http://localhost:8080/liwl_springmvc_annotation/fileupload,开始上传文件,上传文件提交时,url是upload

上传成功以后,返回的是uploadsuccess的页面,返回的url是:http://localhost:8080/liwl_springmvc_annotation/upload

4. 下载文件

4.1 创建后端代码

修改FileUploadController.java,增加

package com.liwl.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

    @RequestMapping(value = "/fileupload",method = RequestMethod.GET)
    public ModelAndView liwanliang() throws ServletException,IOException{
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("uploadpage");
        return modelAndView;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ModelAndView upload(@RequestParam(value = "file") MultipartFile multipartFile,HttpServletRequest request) throws IOException{
        ModelAndView modelAndView = new ModelAndView();

        if (!multipartFile.isEmpty()){
            String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
            String fileName = multipartFile.getOriginalFilename();
            File fileDir = new File(fileDirStr);
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
            File filetmp = new File(fileDir, fileName);
            multipartFile.transferTo(filetmp);

            modelAndView.addObject("filename", ""+fileName);
            modelAndView.setViewName("uploadsuccess");
        } else {
            modelAndView.setViewName("uploadfail");
        }

        return modelAndView;
    }

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void download(HttpServletRequest request,HttpServletResponse response,@RequestParam String filename) throws IOException{
        String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
        File file = new File(fileDirStr, filename);
        byte[] outByte = FileUtils.readFileToByteArray(file);
        String downloadFilename = new String(file.getName().getBytes("utf-8"),"iso-8859-1");
        response.setHeader("Content-Disposition", "attchement;filename="+downloadFilename);
        response.getOutputStream().write(outByte);
        response.getOutputStream().close();
    }
}

4.2 创建前端代码

创建uploadsuccess.jsp,增加下载功能

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<p>
    上传成功!文件名:${filename},<a href="${pageContext.request.contextPath}/download?filename=${requestScope.filename}">点击下载</a>
</p>
</body>
</html>

访问:http://localhost:8080/fileupload,出现上传文件界面。

上传文件成功后,会列出当前的文件名,以及下载后缀

上传成功!文件名:174890324_nb2-1-64.flv,点击下载

点击下载以后,就能够下载上传的flv文件。

posted @ 2022-07-18 15:33  liwldev  阅读(125)  评论(0编辑  收藏  举报