SpringMVC study notes | file upload in SpringMVC

File upload

SpringMVC provides file upload direct support, this support is through the MultipartResolverrealization of which there is a class of its realization: CommonsMultipartResovler.

There is no assembly in the SpringMVC context by default MultipartResolver, so file upload work cannot be handled by default. If you want to use the file upload function of SpringMVC, you need to configure it in the context MultipartResolver.

Configure MultipartResolver

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="1024000"/>
    </bean>

defaultEncoding: Must be pageEncodingconsistent with the attributes of the user JSP in order to correctly parse the content of the form.

In order to CommonsMultipartResovlerwork correctly, you must first add the Jakarta Commons FileUplo and Jakarta Commons io class packages to the classpath.

 
13424350-59e6fb93a56c42fd.png
 

Example: Make a file upload Demo

  • The form is as follows:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title> 
</head>
<body>
    <form action="testFileUpload" method="post" enctype="multipart/form-data">
        File : <input type="file" name="file" />
        Desc : <input type="text" name="desc" />
        <input type="submit" value="submit" />
    </form>
</body>
</html>
  • The configuration file is as follows:
<?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="com.cerr.springmvc"/>
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/webViews/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven />

    <!-- 配置CommonsMultipartResolver -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="1024000"/>
    </bean>
</beans>
  • The method of controller writing is as follows:
package com.cerr.springmvc.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

@Controller
public class SpringMVCTest1 {
    @Autowired
    private HttpServletRequest request;
    
    //上传文件
    @RequestMapping(value = "/testFileUpload")
    public String testFileUpload(@RequestParam("desc") String desc,
                                 @RequestParam("file")MultipartFile file) throws IOException {
//        System.out.println("desc:"+desc);
//        System.out.println("OriginalFilename:"+file.getOriginalFilename());
//        System.out.println("InputStream:"+file.getInputStream());

        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取其在web服务器中路径
        String path = request.getServletContext().getRealPath("/files");

        //创建文件
        File newFile = new File(path,fileName);
        if (!newFile.exists()){
            newFile.createNewFile();
        }
        //输出流
        FileOutputStream outputStream = new FileOutputStream(newFile);
        //输入流
        InputStream inputStream =  file.getInputStream();
        byte [] f = new byte[1024];
        try{
            while(inputStream.read(f) != -1){
                outputStream.write(f);
            }
            inputStream.close();
            outputStream.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        //System.out.println(path);
        return "success";
    }
}

The JSP page accessed after uploading is an empty template page, so the code is not given here.

Guess you like

Origin blog.csdn.net/qq_14810195/article/details/103161206