Рубрики
Без рубрики

Пример загрузки файла Spring MVC

– Пример загрузки файла Spring MVC

Использование пружины MultipartResolver интерфейс для обработки загрузки файлов в веб-приложении, две реализации:

  1. StandardServletMultipartResolver – Анализ составных запросов сервлета 3.0.
  2. CommonsMultipartResolver – Классический commons-fileupload.jar

Инструменты, используемые в этой статье:

  1. Пружина 4.3.5. ВЫПУСК
  2. Мавен 3
  3. Tomcat 7 или 8, причал 9 или любой контейнер сервлета 3.0

В двух словах, в этой статье показано, как обрабатывать загрузку файлов в веб-приложении Spring MVC, а также как обрабатывать популярное исключение максимального превышения размера файла.

P.S Статья обновлена с весны 2.5.x до весны 4.3.x

1. Структура проекта

Стандартная структура проекта Maven.

2. Зависимость от проекта

Стандартные зависимости Spring, не требуется дополнительная библиотека для загрузки файлов.


    4.0.0
    com.mkyong
    spring-mvc-file-upload
    war
    1.0-SNAPSHOT
    Spring MVC file upload

    
        1.8
        4.3.5.RELEASE
        1.2
        3.1.0
        1.1.3
        1.7.12
    

    

        
            org.springframework
            spring-webmvc
            ${spring.version}
            
                
                    commons-logging
                    commons-logging
                
            
        

        
            javax.servlet
            jstl
            ${jstl.version}
        

        
        
            javax.servlet
            javax.servlet-api
            ${servletapi.version}
            provided
        

		
        
            org.slf4j
            jcl-over-slf4j
            ${jcl.slf4j.version}
        

        
            ch.qos.logback
            logback-classic
            ${logback.version}
        

    

    
        

            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.3
                
                    ${jdk.version}
                    ${jdk.version}
                
            

            
            
                org.eclipse.jetty
                jetty-maven-plugin
                9.2.11.v20150529
                
                    10
                    
                        /spring4upload
                    
                
            

            
            
                org.apache.maven.plugins
                maven-eclipse-plugin
                2.9
                
                    true
                    true
                    2.0
                    /spring4upload
                
            

        
    


3. Составной конфигурационный элемент

Создайте класс инициализатора сервлета и зарегистрируйте javax.servlet. Составной конфигурационный элемент

package com.mkyong;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import java.io.File;

public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    private int maxUploadSizeInMb = 5 * 1024 * 1024; // 5 MB

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{SpringWebMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Class[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {

        // upload temp file will put here
        File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));

        // register a MultipartConfigElement
        MultipartConfigElement multipartConfigElement =
                new MultipartConfigElement(uploadDirectory.getAbsolutePath(),
                        maxUploadSizeInMb, maxUploadSizeInMb * 2, maxUploadSizeInMb / 2);

        registration.setMultipartConfig(multipartConfigElement);

    }

}

Просмотрите подпись метода MultipartConfigElement .

public MultipartConfigElement(java.lang.String location,
                              long maxFileSize,
                              long maxRequestSize,
                              int fileSizeThreshold)

4. Конфигурация пружины

Зарегистрировать Составной решатель компонент и возвращает Стандартный сервлет-мультипартрезольвер

package com.mkyong;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({"com.mkyong"})
public class SpringWebMvcConfig extends WebMvcConfigurerAdapter {

	// Bean name must be "multipartResolver", by default Spring uses method name as bean name.
    @Bean
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

	/*
	// if the method name is different, you must define the bean name manually like this :
	@Bean(name = "multipartResolver")
    public MultipartResolver createMultipartResolver() {
        return new StandardServletMultipartResolver();
    }*/

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

}

На этом этапе анализ составных запросов сервлета 3.0 настроен правильно, и вы можете начать загрузку файла.

4. Загрузка Одного Файла

4.1 Обычный тег HTML-формы.




Spring MVC file upload example


4.2 Другая страница для отображения статуса загрузки.



Upload Status

Message : ${message}

4.3 В контроллере сопоставьте загруженный файл с Составным файлом

package com.mkyong.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.StringJoiner;

@Controller
public class UploadController {

	//Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "F://temp//";

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    //@RequestMapping(value = "/upload", method = RequestMethod.POST)
    @PostMapping("/upload") // //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }

        try {

            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message", 
                        "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }

}

5. Загрузка Нескольких Файлов

5.1 Просто добавьте больше входных файлов.




Spring MVC multi files upload example




5.2 В Spring Controller сопоставляет несколько загруженных файлов с Составным файлом []

    //...
	
    @PostMapping("/uploadMulti")
    public String multiFileUpload(@RequestParam("files") MultipartFile[] files,
                                  RedirectAttributes redirectAttributes) {

        StringJoiner sj = new StringJoiner(" , ");

        for (MultipartFile file : files) {

            if (file.isEmpty()) {
                continue; //next pls
            }

            try {

                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);

                sj.add(file.getOriginalFilename());

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        String uploadedFileName = sj.toString();
        if (StringUtils.isEmpty(uploadedFileName)) {
            redirectAttributes.addFlashAttribute("message", 
                        "Please select a file to upload");
        } else {
            redirectAttributes.addFlashAttribute("message", 
                        "You successfully uploaded '" + uploadedFileName + "'");
        }

        return "redirect:/uploadStatus";

    }

    @GetMapping("/uploadMultiPage")
    public String uploadMultiPage() {
        return "uploadMulti";
    }
    //...

6. Обрабатывать превышенный максимальный размер загрузки

Чтобы обработать популярное исключение превышения максимального размера загрузки, объявите @ControllerAdvice и поймайте Составное исключение

package com.mkyong.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {

        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";

    }

	// For commons-fileupload solution
    /*@ExceptionHandler(MaxUploadSizeExceededException.class)
    public String handleError2(MaxUploadSizeExceededException e, RedirectAttributes redirectAttributes) {

        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";

    }*/
}

7. ДЕМОНСТРАЦИЯ

Получите исходный код ниже и протестируйте со встроенным сервером Jetty mvn jetty: запустите .

7.1 Просмотрите pom.xml выше , , встроенный причал развернет веб-приложение в этом /контексте загрузки spring 4 .

project $ mvn jetty:run
//...
[INFO] Started o.e.j.m.p.JettyWebAppContext@341672e{/spring4upload,
	file:/SpringMVCUploadExample/src/main/webapp/,AVAILABLE}{file:/SpringMVCUploadExample/src/main/webapp/}
[WARNING] !RequestLog
[INFO] Started ServerConnector@3ba1308d{HTTP/1.1}{0.0.0.0:8080}
[INFO] Started @3743ms
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 10 seconds.

7.2 Доступ http://localhost:8080/spring4upload

7.3 Выберите файл ‘ MyFirstExcel.xml ‘ и загрузите его.

7.4 Доступ http://localhost:8080/spring4upload/uploadMultiPage

7.5 Выберите несколько файлов и загрузите их.

7.6 Выберите файл размером более 5 Мб, вы посетите эту страницу.

8. Скачать Исходный Код

P.S Для весны 2.5.x попробуйте это Для весны 2.5.x попробуйте это (10 КБ)

Рекомендации

  1. Весенняя Загрузка Файлов
  2. Поддержка составных частей Spring (загрузка файлов)

Оригинал: “https://mkyong.com/spring-mvc/spring-mvc-file-upload-example/”