File upload and file download of spring MVC

Posted by kirk112 on Wed, 09 Feb 2022 09:13:34 +0100

1. File upload

In web development, there are usually file upload operations

The common fileUpload component of Apache organization is used for file upload in general java web development

When multipartfile object is used in spring MVC to accept uploaded files, the name of background parameters must be consistent with the name of the file submitted by the form

Necessary conditions for file upload

  1. Form must be post
  2. The form must have a file field

Enctype = "multipart / form data" of the form

1.1. Copy jar package

1.2. Prepare jsp page

<fieldset>
        <legend>Single file upload</legend>
        <form action="${pageContext.request.contextPath}/upload.do" method="post"             
                       enctype="multipart/form-data">

            full name: <input name="username"><br>
            head portrait: <input type="file" name="headImg"><br>
            <button type="submit">Submit</button>
        </form>
</fieldset>

1.3. Background code

When the MultipartFile object is used in spring MVC to accept uploaded files, the name of the MultipartFile parameter of the background method must be consistent with the name of the file submitted by the form

//When multipartfile object is used in spring MVC to accept uploaded files, the name of background parameters must be consistent with the name of the file submitted by the form
    @RequestMapping("/upload")
    public String singleUpload(MultipartFile headImg,@RequestParam("username")String username) throws IOException {

        System.out.println(headImg.getName());//Get the form name of the uploaded file
        System.out.println(headImg.getContentType());//MIME type
        System.out.println(headImg.getSize());//file size
        System.out.println(headImg.getOriginalFilename());//Get the full name of the uploaded file
        //Get the input stream corresponding to the uploaded file
        //InputStream in = headImg.getInputStream();

        //Create a disk directory for saving files
        File destFile= new File("c:/upload");
        if(!destFile.exists()) {
            destFile.mkdir();
        }
        //Use uuid as the random name of the file
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        //Use FileNameUtils to get the suffix of the uploaded file name
        String extension = FilenameUtils.getExtension(headImg.getOriginalFilename());// Jpg, PNG, etc
        //Create a new file name
        String newFileName = fileName + "."+extension;

        //Create a File object to save the File
        File file = new File(destFile, newFileName);
        //Save file to local disk
        headImg.transferTo(file);

        return "redirect:/upload.jsp";
    }

1.4. Profile upload parser

Profile upload parser: bean Your name is fixed
 use spring expression #{1024*1024}

<!-- Profile upload parser: bean Your name is fixed,Name injection used by the underlying -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- Set the maximum size of the uploaded file to 1 MB -->
    <property name="maxUploadSize" value="#{1024 * 1024}"></property>
</bean>

1.5. Multi file upload

<fieldset>
        <legend>Single file upload</legend>
        <form action="${pageContext.request.contextPath}/uploads.do" method="post" enctype="multipart/form-data">
            File 1: <input type="file" name="headImgs"><br>
            Document 2: <input type="file" name="headImgs"><br>
            Document 3: <input type="file" name="headImgs"><br>
            <button type="submit">Submit</button>
        </form>
    </fieldset>
@RequestMapping("/uploads")
    public String singleUploads(MultipartFile[] headImgs) throws IOException {


        //Create a disk directory for saving files
        File destFile= new File("c:/upload");
        if(!destFile.exists()) {
            destFile.mkdir();
        }
        for (int i = 0; i < headImgs.length; i++) {
            MultipartFile headImg = headImgs[i];

            //Use uuid as the random name of the file
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //Use FileNameUtils to get the suffix of the uploaded file name
            String extension = FilenameUtils.getExtension(headImg.getOriginalFilename());// Jpg, PNG, etc
            //Create a new file name
            String newFileName = fileName + "."+extension;

            //Create a File object to save the File
            File file = new File(destFile, newFileName);
            //Save file to local disk
            try {
                headImg.transferTo(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "redirect:/upload.jsp";
    }

2. File download

For file download, spring MVC does not do too much encapsulation, but uses the original download method

package cn.zj.springmvc.controller;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class DownloadController {
    /*
     * Download File ideas
     * 1. Accept the name of the file to be downloaded, find the file corresponding to the disk according to the file name, and read it into memory to form an input stream
     * 2. Respond the input stream to the browser through the response object (HttpServletResponse) (download)
     *
     * Note: the Web generally only downloads small files
     *
     */
    @RequestMapping("/download")
    public void upload(String fileName ,HttpServletResponse response) throws IOException {
        //0. Judge whether vip, with points, golden beans
        //TODO

        //1. Accept the file name, read the file corresponding to the disk, and create the input stream object

        FileInputStream inputStream = new FileInputStream("C:/"+fileName);

        //2. Get the output stream of the response object
        ServletOutputStream outputStream = response.getOutputStream();


        //3. ISO-08859-1 coding is used for the file name of file download
        //We need to convert the filename of UTF-8 to ISO-8859-1 encoding
        //3.1 first convert the string into byte array in UTF-8
        byte[] bytes = fileName.getBytes("UTF-8");
        //3.2 convert the byte array to string in ISO-8859-1
        fileName = new String(bytes, "ISO-8859-1");


        //4. The content of the response should be in the form of an attachment to the browser (set the response header)
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);

        //5. Send the response file to the browser
        IOUtils.copy(inputStream, outputStream);

    }

}

3. Interceptor of spring MVC

Interceptor: interceptor

The interceptor of Spring MVC , similar to the Filter in Servlet , development, is used to preprocess and post process the Controller.

To use the spring MVC Interceptor:

1) Define interceptor class and implement interface springframework. web. servlet. HandlerInterceptor

2) In ApplicationContext Configuring interceptors in XML

Execution timing of interceptor method:

1):preHandle: the controller method is executed before execution. If the return result is true, it means release. If the return result is false, it means interception (permission interception and login check interception can be done)

2):postHandle: after the controller method is executed, it is executed before the view is rendered (unified response information can be added)

3):afterCompletion: execute after view rendering (handle Controller exception information, record operation log, clean resources, etc.)

3.1. Custom interceptor

public class CheckLoginInterceptor implements HandlerInterceptor {
    //1):preHandle: the controller method is executed before execution. If the return result is true, it means release. If the return result is false, it means interception (permission interception and login check interception can be done)
    // Release: true: false
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        System.out.println("The interceptor executed......");
        //Get login information from Session
        String username = (String)request.getSession().getAttribute("username");
        System.out.println(username);

        if(username !=null) {
            //Release
            return true;
        }else {
            //Jump to the login page
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return false;
        }
    }

    //postHandle: after the controller method is executed, it is executed before the view is rendered (unified response information can be added)
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    //After completion: execute after view rendering (handle Controller exception information, record operation log, clean up resources, etc.)
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}

3.1.1. Interceptor configuration

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

        <!-- to configure springmvc Annotation driven -->
        <mvc:annotation-driven/>



        <!-- Configuring Interceptors  :There can be multiple interceptors-->
        <mvc:interceptors>
            <!--Configure check login interceptor  -->
            <mvc:interceptor>

                <!-- Configure rules for interception
                    Only controller requests will be intercepted, not intercepted jsp page
                    /*
                        Only one level can be intercepted, such as: /list.do /delete.do
                        For example:/user/list.do , /user/delete.do Level 2 cannot intercept
                    /**
                        Can intercept multiple levels, no matter how many levels, such as  /a/b/c/d/list.do
                 -->
                <mvc:mapping path="/**"/>

                <!-- Exclude intercepted addresses. Multiple addresses are separated by commas
                    /user/login.do


                 -->
                <mvc:exclude-mapping path="/user/login.do"/>

                <!-- Type of interceptor -->
                <bean class="cn.zj.ssm.interceptor.CheckLoginInterceptor"/>

            </mvc:interceptor>
        </mvc:interceptors>


</beans>

4. Use poi component to export excel file

Use POI component to process Excel data

Download path: Apache POI - the Java API for Microsoft Documents

4.1. Introductory case

4.1.1. Import jar package

4.1.2. Case code

//Use POI to create excel files locally
    @Test
    public void testName() throws Exception {
        //1. Create data for creating excel locally
        HSSFWorkbook book = new HSSFWorkbook();
        //2. Create a sheet work area
        HSSFSheet sheet = book.createSheet();
        //3. Create a row: starting from 0, representing the first row
        HSSFRow row = sheet.createRow(0);
        //4. Create cells
        HSSFCell cell1 = row.createCell(0);
        //5. Set cell data
        cell1.setCellValue("Zhang San");

        HSSFCell cell2 = row.createCell(1);
        cell2.setCellValue(20);

        //Save data locally
        try {
            book.write(new File("d:/test.xlsx"));
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
    }

 4.2. Use POI to export all user information of the database

// Export user information
    @RequestMapping("/exprot")
    public void export(HttpServletResponse response) {


        //Create data object for POI
        HSSFWorkbook book = new HSSFWorkbook();
        //Create sheet
        HSSFSheet sheet = book.createSheet();
        //Create title column
        HSSFRow titleRow = sheet.createRow(0);
        //Create form cells and set values
        titleRow.createCell(0).setCellValue("number");
        titleRow.createCell(1).setCellValue("full name");
        titleRow.createCell(2).setCellValue("mailbox");
        titleRow.createCell(3).setCellValue("Telephone");

        List<User> users = service.list();
        //Circular students
        for (int i = 0; i < users.size(); i++) {
            //Get each student
            User user = users.get(i);
            //Create student column
            HSSFRow row = sheet.createRow(i+1);
            //Create cells corresponding to student information and set data
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getName());
            row.createCell(2).setCellValue(user.getEmail());
            row.createCell(3).setCellValue(user.getPhone());
        }

        try {
            //Set the response header. The content of the response is in the form of attachment
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String("Student information.xlsx".getBytes(), "ISO-8859-1"));

            book.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

5. Life cycle of spring MVC Controller

Objects created by the Spring container are singleton objects by default

There are three situations for creating spring MVC Controller objects

Request: multiple instances that take effect in a user's request (the user will create a Controller object each time)

Session: the controller object creates an object in a session

If there is a member variable , setting or assignment operation in the controller, you must use , request , to return

 

Topics: Java html webview