Spring Boot (教程十三:附件上传)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gfd54gd5f46/article/details/77004890

GitHub 地址:

https://github.com/asd821300801/Spring-Boot.git



导入依赖的jar包


  • 使用JSP模版


需要在application.properties中配置访问路径

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/page/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp


pom.xml 导入以下依赖

 <dependencies>

    <!-- spring boot web支持 -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>

    <!-- 使用JSP -->
      <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

</dependencies>

  • 使用thymeleaf模版


如果引入thymeleaf模板,那jsp的路径就不生效了,此时文件的路径在:resources/templates/..

0



pom.xml 导入以下依赖

 <dependencies>
     <!-- spring boot web支持 -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>

     <!-- thymeleaf模板依赖. -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
     </dependency>

     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
     </dependency>
 </dependencies>


注意:如果同时使用两种模版引擎,Spring Boot 默认使用Thymeleaf作为模版引擎

扫描二维码关注公众号,回复: 3452452 查看本文章


文件上传控制器


  • FileUploadController.java

包所在:com.example.controller

package com.example.controller;


import java.io.File;

import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



@Controller
@RequestMapping("/upload")
public class FileUploadController {

        /**
         * 上传单个文件
         * 访问路径为:http://ip:port/upload/singleFileUpload.action
         * @return
         */
        @RequestMapping(value = "/singleFileUpload", method = RequestMethod.GET)
        public String singleFileUpload() {
            return "/singleFileUpload";
        }

        /**
         * 上传多个文件
         * 访问路径为:http://ip:port/upload/multipleFilesUpload.action
         * @return
         */
        @RequestMapping(value = "/multipleFilesUpload", method = RequestMethod.GET)
        public String multipleFilesUpload() {
            return "/multipleFilesUpload";
        }



        /**
         * 单文件上传
         * @param file
         * @return
         */
        @RequestMapping(value = "/singleFileUpload", method = RequestMethod.POST)
        @ResponseBody
        public String singleFileUpload(@RequestParam("file") MultipartFile file) {
            if (!file.isEmpty()) {
                //获取源文件名
                String orgName = file.getOriginalFilename();
                System.out.println("原文件名:" + orgName);
                String saveName = UUID.randomUUID() + orgName.substring(orgName.lastIndexOf("."));
                try {
                    file.transferTo(new File("f://image/" + saveName));
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                }
                return "上传成功。";
            } else {
                return "上传失败。";
            }
        }


        /**
         * 多文件上传
         * @param file
         * @return
         */
        @RequestMapping(value = "/multipleFilesUpload", method = RequestMethod.POST)
        @ResponseBody
        public String multipleFilesUpload(@RequestParam("file") MultipartFile[] files) {
            if(files != null && files.length > 0){
                int num = 0;
                for(int i = 0; i < files.length;i++){
                    if (!files[i].isEmpty()) {
                        //获取源文件名
                        String orgName = files[i].getOriginalFilename();
                        System.out.println("原文件名:" + orgName);
                        String saveName = UUID.randomUUID() + orgName.substring(orgName.lastIndexOf("."));
                        try {
                            files[i].transferTo(new File("f://image/" + saveName));
                        } catch (IllegalStateException | IOException e) {
                            e.printStackTrace();
                        }
                        num += 1;
                    }
                }
                return "上传成功数:" + num;
            }
            return "上传失败。";
        }
}

文件上传配置器


  • FileUploadConfiguration.java

包所在:com.example.configuration

package com.example.configuration;

import javax.servlet.MultipartConfigElement;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FileUploadConfiguration {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超出设置页面会抛出异常信息,
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        factory.setMaxFileSize("1024MB"); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("1024MB");
        // Sets the directory location where files will be stored.设置目录位置的文件将被存储。
        //factory.setLocation("f:/image/");
        return factory.createMultipartConfig();
    }
}


注意:如果修改了DispatcherServlet默认配置,则需要设置 “多部件配置元素”,
否则上传文件的时候会出现:“Required request part 'file' is not present” ,具体看代码


  • 修改的文件: SpringbootHelloApplication.java


    @Autowired
    private MultipartConfigElement multipartConfigElement;//注入 “多部件配置元素”

    /**
     * 修改DispatcherServlet默认配置
     *
     * @param dispatcherServlet
     * @author LingDu
     */
    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
        registration.getUrlMappings().clear();

        //这里需要将附件配置设置进去,否则请求不过来 报异常:Required request part 'file' is not present
        registration.setMultipartConfig(multipartConfigElement); 

        registration.addUrlMappings("*.action"); //只有*.action 的请求能通过
        return registration;
    }

测试


  • 上传单个文件

http://localhost:8080/upload/singleFileUpload.action


选择单个文件上传后的结果:

1



  • 上传多个文件

http://localhost:8080/upload/multipleFilesUpload.action


选择多个文件上传后的结果:

2



  • 控制台打印如下信息:

3


  • 到f:/image/目录下查,文件确实是上传上来了。

4



工程结构图

5


猜你喜欢

转载自blog.csdn.net/gfd54gd5f46/article/details/77004890
今日推荐