9.SpringMVC file upload and download

Reprinted: https: //blog.kuangstudy.com/index.php/archives/486/

A .SpringMVC file upload and download

1. Prepare

   File upload project development is one of the most common functions, springMVC can be a good support file uploads, but SpringMVC default context is not equipped MultipartResolver, so it can not handle file uploads work by default. If you want to use Spring file upload function, you need to configure MultipartResolver in context.

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. In 2003, Apache Software Foundation released the open-source Commons FileUpload component, which soon became the best choice Servlet / JSP programmers to upload files.

  • Servlet3.0 specification already provides methods to handle file uploads, but this needs to be done in a Servlet upload.

  • The Spring MVC provides a simpler package.

  • 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 also need to rely on Apache Commons FileUpload component ==.

2. file upload two codes

step:

  1. Add jar package in pom.xml

  2. Placed springmvc-servlet.xml

  3. Write front page

  4. Write back-end

  5. test

(1) a Code:

Add jar package in pom.xml

<! - file upload ->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<-! Servlet-api to import high version ->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Placed springmvc-servlet.xml

<! - File Uploads Configuration ->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <! - encoding format requested, must coincide jSP pageEncoding properties, in order to read the contents of the correct form, the default is ISO-8859-1 ->
    <property name="defaultEncoding" value="utf-8"/>
    <! - upload file size limit in bytes (10485760 = 10M) ->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>

Write front page

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

  <H1> embodiment 1 </ h1>
  <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload">
  </form>

  </body>
</html>

Write back-end

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@RestController
public class FileController {


    // @RequestParam ( "File") will package name = file controls the resulting file into CommonsMultipartFile objects
     // bulk upload CommonsMultipartFile compared to the array 
    @ RequestMapping ( "/ the Upload" )
     public String fileUpload (@RequestParam ( "File") File CommonsMultipartFile, the HttpServletRequest Request) throws IOException {

        // 获取statement Subject: File.GetOriginalFilename (); 
        String UploadFileName = File.GetOriginalFilename ();

        // If the file name is empty, straight back home! 
        IF ( "" .equals (uploadFileName)) {
             return "filename is NULL!" ;
        }
        System.out.println ( "upload file name:" + uploadFileName);

        // upload path to save the settings 
        String path = request.getServletContext () getRealPath ( "/ the Upload." );
         // If the path does not exist, create a 
        File realpath = new new File (path);
         IF (! RealPath.exists ()) {
            realPath.mkdir();
        }
        System.out.println ( "upload files to save address:" + realpath);

        IS the InputStream = file.getInputStream (); // file input stream 
        the OutputStream OS = new new a FileOutputStream ( new new File (realpath, uploadFileName)); // file output stream

        //读取写出
        int len=0;
        byte[] buffer = new byte[1024];
        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return "uploaded successfully!" ;
    }
    
}

test was successful!

(1) Code II:

Using file.Transto to save the uploaded files

Write front page

<H1> to save files uploaded using file.Transto </ h1>
<form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
  <input type="file" name="file"/>
  <input type="submit" value="upload">
</form>

Write back-end

/*
 * Use file.Transto to save the uploaded files
 */
@RequestMapping("/upload2")
public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

    // upload path to save the settings 
    String path = request.getServletContext () getRealPath ( "/ the Upload." );
    File realPath = new File(path);
    if (!realPath.exists()){
        realPath.mkdir();
    }
    // upload address 
    System.out.println ( "upload files to save address:" + realpath);

    // method CommonsMultipartFile direct write file (note this time) 
    file.transferTo ( new new File (realpath + "/" + file.getOriginalFilename ()));

    return "uploaded successfully!" ;
}

test was successful!

3. Download

Download steps:

  1. Response in response to the first set

  2. Read a file - InputStream

  3. Write files - OutputStream

  4. Perform an operation

  5. Close stream (the first switch)

Write front page

<a href="${pageContext.request.contextPath}/download">点击下载</a>

Write back-end

upload files in the project directory folder packed the code to get a picture .png images downloaded

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
    //要下载的图片地址
    String  path = request.getServletContext().getRealPath("/upload");
    FileName String = "Pictures Code .png" ;

    // 1, response is provided in response header 
    response.reset (); // set the page is not cached, empty Buffer 
    response.setCharacterEncoding ( "UTF-. 8"); // character encoding 
    response.setContentType ( "multipart / form-data ") ; // binary transmission data
     // setting response header 
    response.setHeader ( "the Content-Disposition" ,
             "Attachment; fileName =" + the URLEncoder.encode (fileName, "UTF-. 8" ));

    File File = new new File (path, fileName);
     // 2, read the file - the input stream 
    the InputStream INPUT = new new the FileInputStream (File);
     // . 3, write the file - the output stream 
    the OutputStream OUT = response.getOutputStream () ;

    byte [] = BUFF new new  byte [1024 ];
     int index = 0 ;
     // . 4, performs the writing operation 
    the while (-1 = (index = input.read (BUFF))! ) {
        out.write(buff, 0, index);
        out.flush();
    }
    out.close();
    input.close();
    return null;
}

test was successful!

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12340010.html