SpringBoot上传单个文件和多个文件

在网络应用中,注册用户时上传文件已经是屡见不鲜的功能了,在springboot中实现这个功能变得异常简单方便。

下面我们来演示一下使用springboot来实现一下功能;

上传单个文件并绑定变量值、上传多个文件(多个文件为相同name)并绑定变量值、同时上传多个文件和单个文件(多个文件为相同的name;单个文件为其他name值)

准备工作首先我们需要一个可运行的springBoot项目这个项目的pom.xml文件内容为:

pom.xml

<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.3.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>
在src/resouces/templates/下有以下html文件:

multipleFile.html(上传多个文件和绑定值页面)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
   <head>
        <title>上传多个文件</title>
   </head>
   <body>
        <h1 th:inline="text">上传多个文件</h1>
        <form action="/uploadFiles" method="POST" enctype="multipart/form-data">
        		<input type="text" name="name"/>
        		<input type="text" name="age"/>
        	 <p>文件1:<input type="file" name="myfiles"/></p>
        	 <p>文件2:<input type="file" name="myfiles"/></p>
        	 <p>文件3:<input type="file" name="myfiles"/></p>
        	 
          	 <p><input type="submit" value="上传" /></p>
        </form>
   </body>
</html>
multipleFileAndOneFile.html(上传多个页面和单个文件并绑定值页面)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
   <head>
        <title>上传多个文件</title>
   </head>
   <body>
        <h1 th:inline="text">上传多个文件</h1>
        <form action="/uploadFilesAndOneFile" method="POST" enctype="multipart/form-data">
        		<input type="text" name="name"/>
        		<input type="text" name="age"/>
        	 <p>单文件:<input type="file" name="myfile"/></p>
        	 <p>文件1:<input type="file" name="myfiles"/></p>
        	 <p>文件2:<input type="file" name="myfiles"/></p>
        	 <p>文件3:<input type="file" name="myfiles"/></p>
        	 
          	 <p><input type="submit" value="上传" /></p>
        </form>
   </body>
</html>

OneFile.html(上传单个文件并绑定值页面)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
   <head>
        <title>上传一个文件</title>
   </head>
   <body>
        <h1 th:inline="text">上传一个文件</h1>
        <form action="/uploadOneFile" method="POST" enctype="multipart/form-data">
        	 <p>文件:<input type="file" name="myfile"/></p>
        	 <input type="text" name="name"/>
        	 <input type="text" name="age"/>
          	 <p><input type="submit" value="上传" /></p>
        </form>
   </body>
</html>
result.html(上传结果页面)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
   <head>
        <title>上传文件结果</title>
   </head>
   <body>
         <h1>上传结果:<lable th:text="${result}"></lable></h1>
   </body>
</html>
项目结构为:




之后再Application.java中实现上传文件逻辑:

package com.ys.springbootfileupload;

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

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@SpringBootApplication
@Controller
public class Application 
{
    public static void main( String[] args )
    {
    	SpringApplication.run(Application.class, args);  
    }
    
    /**
     * 方便测试上传一个或者多个文件的路径
     * @param name
     * @return
     */
    @RequestMapping("/FileUpload/{fileHtml}")
    public String uploadFile(@PathVariable("fileHtml") String name){
    	return name;
    }
    
    /**
     * 上传一个文件
     * @param myfile
     * @param name
     * @param age
     * @param map
     * @return
     */
    @RequestMapping("/uploadOneFile")
    public String uploadFile(MultipartFile myfile,String name,String age,Model map){
    	try {
    		String filename = myfile.getOriginalFilename();
			myfile.transferTo(new File("E:\\Young\\verfiyImg\\"+UUID.randomUUID()+"."+filename.substring(filename.lastIndexOf(".")+1)));
			
			System.out.println("接收到的name: "+name+", age: "+age+" 文件名: "+filename);
			map.addAttribute("result", "succeed");
		} catch (IllegalStateException | IOException e) {
			map.addAttribute("result", "fail");
			e.printStackTrace();
		}
    	return "result";
    }
    
    /**
     * 上传多个文件
     * @param myfiles
     * @param name
     * @param age
     * @param map
     * @return
     */
    @RequestMapping("/uploadFiles")
    public String ArrayFiles(@RequestParam("myfiles") MultipartFile[] myfiles,String name,String age,Model map){
    	try {
    		StringBuilder builder = new StringBuilder();
			for (int i = 0; i < myfiles.length; i++) {
				String filename = myfiles[i].getOriginalFilename();
				builder.append(filename+", ");
				myfiles[i].transferTo(new File("E:\\Young\\verfiyImg\\"+UUID.randomUUID()+"."+filename.substring(filename.lastIndexOf(".")+1)));
			}
			System.out.println("接收到的name: "+name+", age: "+age+" 文件名: ["+builder.toString().substring(0, builder.toString().length()-2)+"]");
			map.addAttribute("result", "succeed");
		} catch (IllegalStateException | IOException e) {
			map.addAttribute("result", "fail");
			e.printStackTrace();
		}
    	return "result";
    }
    
    
    /**
     * 同时上传多个文件和一个文件
     * @param myfiles
     * @param name
     * @param age
     * @param map
     * @return
     */
    @RequestMapping("/uploadFilesAndOneFile")
    public String ArrayFilesAndOneFile(@RequestParam("myfiles") MultipartFile[] myfiles,MultipartFile myfile,String name,String age,Model map){
    	try {
    		//用于接收文件名
    		StringBuilder builder = new StringBuilder();
    		//出来多个文件
			for (int i = 0; i < myfiles.length; i++) {
				String filename = myfiles[i].getOriginalFilename();
				builder.append(filename+", ");
				myfiles[i].transferTo(new File("E:\\Young\\verfiyImg\\"+UUID.randomUUID()+"."+filename.substring(filename.lastIndexOf(".")+1)));
			}
			//处理单个文件
			String filename = myfile.getOriginalFilename();
			myfile.transferTo(new File("E:\\Young\\verfiyImg\\"+UUID.randomUUID()+"."+filename.substring(filename.lastIndexOf(".")+1)));
			System.out.println("接收到的name: "+name+", age: "+age+" 多文件文件名: ["+builder.toString().substring(0, builder.toString().length()-2)+"]"+" 单文件名:"+filename);
			map.addAttribute("result", "succeed");
		} catch (IllegalStateException | IOException e) {
			map.addAttribute("result", "fail");
			e.printStackTrace();
		}
    	return "result";
    }
    
    /**
     * 对上传的文件进行限制
     * @return
     */
//    @Bean 
//    public MultipartConfigElement multipartConfigElement() { 
//         MultipartConfigFactory factory = new MultipartConfigFactory();
//          设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了;
//         factory.setMaxFileSize("128KB"); //KB,MB
//         /// 设置总上传数据总大小
//         factory.setMaxRequestSize("256KB"); 
//         //Sets the directory location wherefiles will be stored.
//         //factory.setLocation("路径地址");
//         return factory.createMultipartConfig(); 
//     } 
}

以上就是上传文件逻辑实现,main方法启动springboot应用,uploadFile方法是方便跳转到上传一个文件或者多个文件的页面的controller,multipartConfigElement方法是对上传文件做一定的限制。

之后运行main方法;

1.测试上传单个文件:在浏览器中访问http://localhost:8080/FileUpload/OneFile


指定表单值和文件,并点击上传:
控制台输出:


上传结果:


查看存放文件的路径是否有刚刚上传的文件:


结果:上传成功,文件中也正确存放了文件。


2.上传多个文件:

访问http://localhost:8080/FileUpload/multipleFile


指定表单值和文件,并点击上传:
控制台输出:


上传结果:


查看存放文件的路径是否有刚刚上传的文件:


结果:上传成功,文件中也正确存放了文件。


3.同时上传多个文件(多个文件为一组拥有相同的name)和单个文件

访问http://localhost:8080/FileUpload/multipleFileAndOneFile


指定表单值和文件,并点击上传:
控制台输出:


上传结果:


查看存放文件的路径是否有刚刚上传的文件:


到此单个文件上传、多个文件上传、单个和多个文件一起上传的情况都已经成功。

注意上传多个文件的时候我们应该用@RequestParam("myfiles")注解指定多个文件的name、之后我们可以使用multipartConfigElement来限制上传文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值