SpringBoot的文件上传

Posted yux3344

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot的文件上传相关的知识,希望对你有一定的参考价值。

一:添加commons-fileupload依赖

打开pom文件添加

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
</dependency>

  

二:添加系统变量

打开core→constant文件,添加文件保存路径

//文件上传储存的地址
public static final String SAVEFILEPATH = "F://img";

  

三:添加文件上传限制

application.properties中添加

spring.http.multipart.enabled=true #默认支持文件上传.
spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.
spring.http.multipart.location= # 上传文件的临时目录
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持请求大小

  

  

四:创建文件上传工具类

创建core→utils→UploadActionUtil.java

package com.example.demo.core.utils;

import com.example.demo.core.constant.ProjectConstant;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yux
 * 文件上传控制器
 */
public class UploadActionUtil {

	public static List<String> uploadFile(HttpServletRequest request) throws Exception {
		List<String> list = new ArrayList<>();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iterator = multiRequest.getFileNames();
			while (iterator.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iterator.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
					if (myFileName.trim() != "") {
						String fileTyps = myFileName.substring(myFileName.lastIndexOf("."));
						// String tempName="demo"+fileTyps;
						String tempName = UUID.randomUUID().toString() + fileTyps;
						// 创建文件夹
						String folderPath = ProjectConstant.SAVEFILEPATH + File.separator + folderName();
						File fileFolder = new File(folderPath);
						if (!fileFolder.exists() && !fileFolder.isDirectory()) {
							fileFolder.mkdirs();
						}
						File uploadFile = new File(folderPath + File.separator + tempName);
						file.transferTo(uploadFile);
						myFileName = folderName() + File.separator + tempName;
						list.add(ProjectConstant.SAVEFILEPATH + "//" + myFileName);
					}
				}
			}
		}
		return list;
	}

	/**
	 * 得年月日的文件夹名称
	 *
	 * @return
	 */
	public static String getCurrentFilderName()  throws Exception{
		Calendar now = Calendar.getInstance();
		return now.get(Calendar.YEAR) + "" + (now.get(Calendar.MONTH) + 1) + "" + now.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 创建文件夹
	 *
	 * @param filderName
	 */
	public static void createFilder(String filderName) throws Exception {
		File file = new File(filderName);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
	}

	/**
	 * 文件扩展名
	 *
	 * @param fileName
	 * @return
	 */
	public static String extFile(String fileName)  throws Exception{
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 当前日期当文件夹名
	 *
	 * @return
	 */
	public static String folderName() throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(new Date());
		return str;
	}
}

  

五:创建UploadFileController

package com.example.demo.controller;

import com.example.demo.core.ret.RetResponse;
import com.example.demo.core.ret.RetResult;
import com.example.demo.core.utils.UploadActionUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/uploadFile")
public class UploadFileController {

    @PostMapping("/upload")
    public RetResult<List<String>> upload(HttpServletRequest httpServletRequest) throws Exception {
        List<String> list = UploadActionUtil.uploadFile(httpServletRequest);
        return RetResponse.makeOKRsp(list);
    }
}

  

六:测试

打开postman

输入localhost:8080/uploadFile/upload

注意:请求参数如下

 

以上是关于SpringBoot的文件上传的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot2----拦截器和文件上传功能

java Ftp上传创建多层文件的代码片段

SpringBoot单文件与多文件上传

springboot实现简单的文件上传

上传文件慢,SpringBoot分片上传文件

上传文件慢,SpringBoot分片上传文件