分享知识-快乐自己:SpringMvc中的单多文件上传及文件下载

摘要:SpringMvc中的单多文件上传及文件下载:(以下是核心代码(拿过去直接能用)不谢)

<!--设置文件上传需要的jar-->
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
</dependency>

ControllerWelcome 控制器类:

package controller;
import bean.User;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * @author asus
 */
@Controller
@RequestMapping("/user")
public class ControllerWelcome {

  //单文件上传(User对象的属性名与表单中的name名一致方可自动映射到值)
    @RequestMapping("/upload")
    public ModelAndView upload(User user, MultipartFile picPath, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("Welcome");
        //获取服务器路径
        String realPath = session.getServletContext().getRealPath("/upload/");
        //判断是否存在,不存在则创建
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        //获取源文件名称
        String originalFilename = picPath.getOriginalFilename();
        String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + originalFilename;
        File file1 = new File(realPath, fileName);
        try {
            picPath.transferTo(file1);
            System.out.println("用户名为:" + user.getUseName());
            System.out.println("上传成功:" + realPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }
  //多文件上传(User对象中的属性名与表单的name名一致方可自动映射到值)
    @RequestMapping("/uploads")
    public ModelAndView uploads(User user, @RequestParam MultipartFile[] picPath, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("Welcome");
        //获取服务器路径
        String realPath = session.getServletContext().getRealPath("/upload/");
        //判断是否存在,不存在则创建
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        for (MultipartFile temp : picPath) {
            //获取源文件名称
            String originalFilename = temp.getOriginalFilename();
            String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + originalFilename;
            File file1 = new File(realPath, fileName);
            try {
                temp.transferTo(file1);
                System.out.println("用户名为:" + user.getUseName());
                System.out.println("上传成功:" + realPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return modelAndView;
    }

    //文件下载
    @RequestMapping(value = "/download", method = RequestMethod.GET) //匹配的是href中的download请求
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename
    ) throws IOException {
        //从我们的上传文件夹中去取
        String downloadFilePath = "E:\\idealCase\\CourseNotes\\SpringMvcCase\\SpringMvcCode06\\target\\SpringMvcCode06\\upload";
        //新建一个文件
        File file = new File(downloadFilePath + File.separator + filename);
        //http头信息
        HttpHeaders headers = new HttpHeaders();
        //设置编码
        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");

        headers.setContentDispositionFormData("attachment", downloadFileName);

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);

    }
}

核心配置文件:Spring-view.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--指定Controller扫描器-->
    <context:component-scan base-package="controller"/>
    <!--配置试图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <!--单个文件大小-->
        <property name="maxUploadSizePerFile" value="100000"/>
        <!--文件总大小-->
        <property name="maxUploadSize" value="100000"/>
    </bean>

</beans>

web.xml 配置文件:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--设置乱码-->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--设置核心控制器-->
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:Spring-*.xml</param-value>
    </init-param>
    <!--优先加载-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

index.jsp 前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<body>
<h2>Hello World!</h2>
<fieldset>
    <legend>单文件上传:</legend>
    <form action="/user/upload" method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="useName"><br/>
        文件一:<input type="file" name="picPath">
        <input type="submit" value="提交">
    </form>
</fieldset>
<br/><br/>
<fieldset>
    <legend>多文件上传:</legend>
    <form action="/user/uploads" method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="useName"><br/>
        文件一:<input type="file" name="picPath">
        文件一:<input type="file" name="picPath">
        <input type="submit" value="提交">
    </form>
</fieldset>
<br/><br/>
<fieldset>
    <legend>文件下载</legend>
    <a href="/user/download?filename=1537854894247新建文本文档.txt">
        文件下载:1537854894247新建文本文档.txt</a>
</fieldset>
</body>
</html>

 

posted @ 2018-09-25 14:09  GDBD  阅读(273)  评论(0编辑  收藏  举报