SpringMVC Java framework (five) file upload and download

Reference blog: https://www.cnblogs.com/hellokuangshen/p/11289940.html

File upload and download

springMVC can be a good support file uploads, but SpringMVC default context is not equipped MultipartResolver, therefore by default it can not handle file uploads work. If you want to use Spring file upload function, you need to configure MultipartResolver in context.

Ready to work

Distal form requires: In order to upload a file, the form must be set to the POST method, and enctype to multipart / form-data. Only in this case, the browser will send the user to select a file to the server as binary data;

The enctype attribute of the form to be a detailed description:

  • application / x-www = form-urlencoded: default, only processes the attribute value of the form field values, the value of the form field will form with this encoding process of encoding into a URL.
  • multipart / form-data: encoding this manner will form a binary data stream is processed, the contents of this field specifies the file encoding file will be packaged into request parameters, not the character encoding.
  • text / plain: In addition to converting spaces into "+" sign, the other characters are not doing the encoding process, this method is applicable to send mail directly through the form.
<form action="" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit">
</form>

Once set to enctype multipart / form-data, i.e., the browser will adopt the binary stream processed form data, and for processing the uploaded file involves parsing an HTTP response to the original server side.

Spring MVC file upload provide direct support for this support is MultipartResolver plug and play implementation. Spring MVC using Apache Commons FileUpload technology to achieve a MultipartResolver implementation class: CommonsMultipartResolver. Therefore, SpringMVC file upload component also relies on the Apache Commons FileUpload.

In springmvc-servlet.xml profile as follows:

note! ! ! The bena's id must be: multipartResolver, or upload files will be reported 400 errors! Here we planted over the pit, lesson!

<!--文件上传配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

In addition, we also need to import jar package file upload, commons-fileupload, Maven will automatically help us to import his dependencies commons-io package;

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

We will use it to achieve class CommonsMultipartFile, common methods

String getOriginalFilename (): Gets formerly known as the uploaded file
InputStream getInputStream (): Gets file stream
void transferTo (File dest): Save the file to a directory to upload the file
we go to the actual test

springMVC Upload Files

Method 1: The flow of upload files

controller file:

//文件上传:流
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //1.获得文件名
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
            return "文件不存在";
        }
        //2.上传文件保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //3.上传文件
        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(realPath, filename));

        int len = 0;
        byte[] buffer =  new byte[1024];

        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }

        //4.关闭流
        os.close();
        is.close();
        return "上传完毕";
    }

Front page:

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

<form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload2">
    <input type="file" name="file">
    <<input type="submit">
</form>

</body>
</html>

Output results:
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

Using file.Transto to upload

controller:

文件上传:CommonsMultipartFile
    @RequestMapping(value = "/upload2")
    @ResponseBody
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上传文件保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }

        //transferTo:将文件写入到磁盘,参数就是一个文件
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));

        return "上传完毕";
    }

Other file configuration unchanged

Complete project realization

Project structure:
Here Insert Picture Description

pom.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>demo07_springmvc_file_intercepter</artifactId>
    <packaging>war</packaging>

    <name>demo07_springmvc_file_intercepter Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--文件上传和下载的包commons-fileupload,依赖于commons-io-->
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>demo07_springmvc_file_intercepter</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>


web.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--配置过滤器-->
  <filter>
    <filter-name>myFilter</filter-name>
    <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>-->
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <!--/*  包括.jsp-->
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

springmvc-servlet.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--配置过滤器-->
  <filter>
    <filter-name>myFilter</filter-name>
    <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>-->
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <!--/*  包括.jsp-->
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

fileUploadController file:

package com.kuang.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.security.util.Length;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

@Controller
public class FileUploadController {

    //文件上传:流
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //1.获得文件名
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
            return "文件不存在";
        }
        //2.上传文件保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //3.上传文件
        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(realPath, filename));

        int len = 0;
        byte[] buffer =  new byte[1024];

        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }

        //4.关闭流
        os.close();
        is.close();
        return "上传完毕";
    }

    //文件上传:CommonsMultipartFile
    @RequestMapping(value = "/upload2")
    @ResponseBody
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上传文件保存路径
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }

        //transferTo:将文件写入到磁盘,参数就是一个文件
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));

        return "上传完毕";
    }

}

Download achieve

Download the steps of:
setting the first response in response
to read the file - InputStream
write file - OutputStream
performs an operation
to close the stream (the first switch)

Code:

@RequestMapping(value="/download")
    public String downloads(HttpServletResponse response) throws Exception{
        //要下载的图片地址
        String    path = "C:/Users/Administrator/Desktop/";
        String  fileName = "1.png";

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path,fileName);
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

Published 84 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/yalu_123456/article/details/98884771