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来限制上传文件。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于Spring Boot的FTP并行上传多个文件的示例代码: ``` @Service public class FtpService { @Value("${ftp.host}") private String ftpHost; @Value("${ftp.port}") private int ftpPort; @Value("${ftp.username}") private String ftpUsername; @Value("${ftp.password}") private String ftpPassword; private FTPClient ftpClient; /** * 获取FTP连接 * * @return FTPClient对象 * @throws IOException */ private FTPClient getFtpClient() throws IOException { if (ftpClient == null) { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort); ftpClient.login(ftpUsername, ftpPassword); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); } return ftpClient; } /** * 并行上传多个文件 * * @param fileMap 文件Map,key为文件名,value为文件流 * @param dirPath 上传目录路径 * @throws IOException * @throws InterruptedException */ public void uploadFiles(Map<String, InputStream> fileMap, String dirPath) throws IOException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(fileMap.size()); List<Future<Void>> futures = new ArrayList<>(); for (Map.Entry<String, InputStream> entry : fileMap.entrySet()) { String fileName = entry.getKey(); InputStream inputStream = entry.getValue(); futures.add(executorService.submit(() -> { uploadFile(inputStream, dirPath, fileName); return null; })); } for (Future<Void> future : futures) { future.get(); } executorService.shutdown(); } /** * 上传单文件 * * @param inputStream 文件流 * @param dirPath 上传目录路径 * @param fileName 文件名 * @throws IOException */ private void uploadFile(InputStream inputStream, String dirPath, String fileName) throws IOException { FTPClient ftpClient = getFtpClient(); ftpClient.changeWorkingDirectory(dirPath); ftpClient.enterLocalPassiveMode(); boolean success = ftpClient.storeFile(fileName, inputStream); if (!success) { throw new IOException("Failed to upload file: " + fileName); } } /** * 关闭FTP连接 * * @throws IOException */ public void close() throws IOException { if (ftpClient != null && ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } } ``` 在上述代码中,`FtpService`是FTP上传服务的实现类,其中`uploadFiles`方法使用了Java并发编程中的`ExecutorService`和`Future`来实现多个文件并行上传。`uploadFile`方法用于上传单文件。 使用时,只需在Spring Boot的配置文件中添加FTP的相关配置,然后在需要上传文件的地方调用`FtpService`的`uploadFiles`方法即可。 需要注意的是,由于FTP的上传速度可能受到网络带宽等因素的影响,因此在上传大量文件时,建议适当控制并发数,以避免FTP服务器负载过高。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值