Spring MVC文件上传和下载

依然范特西╮ 提交于 2019-12-04 06:21:26

Spring文件上传(单文件上传):

  

  首先导入依赖: 

  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

  

  配置applicationContext.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--扫描注解-->
    <context:component-scan base-package="cn.mvc"></context:component-scan>
    <!--Spring支持MVC注解-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--试图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:default-servlet-handler/>


    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxInMemorySize" value="5000000"/>

    </bean>


</beans>

 

  创建FileUpLoad类:

package cn.mvc.fileupload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/fileUpLoad")
public class FileUpLoad {

    @RequestMapping("/fileUp")
    public String fileupload(HttpSession session, MultipartFile file, String auth) throws IOException {
        System.out.println(auth);
        System.out.println(file);
        if(!file.isEmpty()){
            String filename = file.getOriginalFilename();
            String path = session.getServletContext().getRealPath("/WEB-INF/upload");
            File upfile = new File(path+"\\"+filename);
            file.transferTo(upfile);

        }


        return "index";
    }

}

 

  两个页面Upload和index页面:

<%--
  Created by IntelliJ IDEA.
  User: WangDaYe
  Date: 2019/11/11
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>FileUp</title>
</head>
<body>
    <form action="/fileUpLoad/fileUp" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
       <%-- <input type="file" name="files">
        <input type="file" name="files">--%>

        <input type="text" name="auth">
        <input type="submit" value="提交">
    </form>

</body>
</html>
<%@page language="java" pageEncoding="utf-8" autoFlush="true" isELIgnored="false" contentType="text/html; utf-8"%>

<html>
<body>

    <h2>Hello World!</h2>
   <%-- <h1>文件上传</h1>
    <form action="" method="post" enctype="multipart/form-data" >
        用户名:<input type="text" name="username" ><br/>
        文件上传:<input type="file" name="image" ><br/>
        <input type="submit" ><br/>
    </form>

    <h1>文件下载</h1>
    <a href="">下载</a>
    <a href="">下载2</a>--%>

</body>
</html>

 

  运行 添加文件:

 

 提交之后添加成功 跳转到index页面

 

项目里就会出现:

  

 

 

 

多文件上传:

  

  多文件上传只需修改如下两处

  1.

 

<%--
  Created by IntelliJ IDEA.
  User: WangDaYe
  Date: 2019/11/11
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>FileUp</title>
</head>
<body>
    <form action="/fileUpLoad/fileUps" method="post" enctype="multipart/form-data">
        <input type="file" name="files">
          <input type="file" name="files">
        <input type="file" name="files">

        <input type="text" name="auth">
        <input type="submit" value="提交">
    </form>

</body>
</html>

 

  2.

package cn.mvc.fileupload;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;


@Controller
@RequestMapping("/fileUpLoad")
public class FileUpLoad {


    @RequestMapping("/fileUps")
    public String fileuploads(HttpSession session, @RequestParam MultipartFile[] files, String auth) throws IOException {
        System.out.println(auth);
        System.out.println(files);
        for (MultipartFile filee:files) {

            if(!filee.isEmpty()){
                String filename = filee.getOriginalFilename();
                String path = session.getServletContext().getRealPath("/WEB-INF/upload");
                File upfile = new File(path+"\\"+filename);
                filee.transferTo(upfile);

            }
        }

        return "index";
    }

}

 

  测似结果和上边一样只是多个文件而已

 

文件下载:

 

import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Component
@Scope("prototype") 
@RequestMapping("/downloadFile")
public class DownloadAction
{
 
    @RequestMapping("download")  
    public ResponseEntity<byte[]> download() throws IOException {  
        String path="D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\springMVC\\WEB-INF\\upload\\图片10(定价后).xlsx";
        File file=new File(path);
        HttpHeaders headers = new HttpHeaders();  
        String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName); 
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),  
                                          headers, HttpStatus.CREATED);  
    }  
}

 

 
<a href="./downloadFile/download" >下载</a>

 在页面里面写上边一句,便可以下载文件

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!