您的位置:首页 > 编程语言 > Java开发

SpringBoot + MultipartFile 实现文件上传以及文件转移的功能以及配置全局捕获上传文件过大异常

2019-03-15 13:06 1061 查看

2019-03-15
话不多说直接上代码
application.yml:因为Linux环境与Windows环境路径不一致,暂时用Windows环境测试

server:
port: 8891

#文件上传Windows
upload:
path:
#临时目录
temporary: E:/upload/temporary/
#正式目录
formal: E:/upload/formal/
multipart:
#单个文件最大内存
maxFileSize: 512KB
#所有文件最大内存
maxRequestSize: 5MB

#文件上传Linux
#upload:
#  path:
#    #临时目录
#    temporary: /usr/upload/temporary/
#    #正式目录
#    formal: /usr/upload/formal/
#  multipart:
#    #单个文件最大内存
#    maxFileSize: 512KB
#    #所有文件最大内存
#    maxRequestSize: 5MB

spring:
resources:
#静态资源访问
static-locations: file:${upload.path.temporary},file:${upload.path.formal}

FilesConfig:读取配置文件中文件上传配置

/**
* @Author Qin
* @Date 2019-03-11 13:21
*/
@Component
@Data
public class FilesConfig {

/**
* 单文件上传最大内存
*/
@Value("${upload.multipart.maxFileSize}")
private String maxFileSize;

/**
* 多文件上传最大内存
*/
@Value("${upload.multipart.maxRequestSize}")
private String maxRequestSize;

/**
* 文件上传临时目录
*/
@Value("${upload.path.temporary}")
private String temporaryPath;

/**
* 文件上传正式目录
*/
@Value("${upload.path.formal}")
private String formalPath;
}

FilesUploadService:文件上传Service,返回文件名称

/**
* 文件上传
*
* @Author Qin
* @Date 2019-03-11 13:28
*/
public class UploadService {
/**
* 文件上传时间
*
* @return
*/
public static String getUploudTime() {
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
return df.format(date);
}

/**
* 给原文件取新的名称
*
* @param fileOriginName
* @return
*/
public static String getFileName(String fileOriginName) {
return UUID.randomUUID().toString().replace("-", "") + fileOriginName.substring(fileOriginName.lastIndexOf("."));
}

/**
* 单文件上传
*
* @param file 文件
* @param path 文件上传路径
* @return
* @throws IOException
*/
public static String uploadOne(MultipartFile file, String path) throws IOException {
String uploudTime = UploadService.getUploudTime();
//新的文件存放路径加上新的文件名
String newPath = path + uploudTime + "/" + UploadService.getFileName(file.getOriginalFilename());
File file1 = new File(newPath);
//判断文件目录是否存在
if (!file1.getParentFile().exists()) {
//创建文件存放目录
//无论是几个/,都是创建一个文件夹
//mkdirs(): 创建多层目录,如:E:/upload/2019
//mkdir(): 只创建一层目录,如:E:upload
//如果不加这一行不会创建新的文件夹,会报系统找不到路径
file1.getParentFile().mkdirs();
}
//存储文件
file.transferTo(file1);
//去掉目录名,保留文件总体路径,通过该路径访问图片
String filename = newPath.substring(newPath.lastIndexOf(path)).replace(path, "");
return filename;
}

/**
* 多文件上传
*
* @param files 文件
* @param path  文件上传路径
* @return
* @throws IOException
*/
public static String uploadMore(MultipartFile[] files, String path) throws IOException {
//多文件文件名
String uploadName = null;
String uploudTime = UploadService.getUploudTime();
for (MultipartFile file : files) {
//新的文件存放路径加上新的文件名
String newPath = path + uploudTime + "/" + UploadService.getFileName(file.getOriginalFilename());
File file1 = new File(newPath);
//判断文件目录是否存在
if (!file1.getParentFile().exists()) {
//创建文件存放目录
//无论是几个/,都是创建一个文件夹
//mkdirs(): 创建多层目录,如:E:/upload/2019
//mkdir(): 只创建一层目录,如:E:upload
//如果不加这一行不会创建新的文件夹,会报系统找不到路径
file1.getParentFile().mkdirs();
}
//存储文件
file.transferTo(file1);
if (uploadName == null) {
uploadName = newPath.substring(newPath.lastIndexOf(path)).replace(path, "");
} else {
uploadName = uploadName + "," + newPath.substring(newPath.lastIndexOf(path)).replace(path, "");
}
}
return uploadName;
}
}

FilesUploadController:文件上传Controller同时包含文件转移

/**
* @Author Qin
* @Date 2019-03-11 10:54
*/
@RestController
@RequestMapping("/api/file")
public class FilesUploadController {

@Autowired
private FilesConfig filesConfig;

/**
* 设置文件上传大小:在配置文件中限定
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize(filesConfig.getMaxFileSize());
//设置总上传数据总大小
factory.setMaxRequestSize(filesConfig.getMaxRequestSize());
return factory.createMultipartConfig();
}

/**
* 单文件上传
* @param file
* @return
* @throws IOException
*/
@PostMapping("/uploadOne")
public JsonResult uploadOne(MultipartFile file) throws IOException {
String uploadOne = UploadService.uploadOne(file, filesConfig.getTemporaryPath());
return ResponseResult.Success(ResultCodeEnums.SUCCESS,uploadOne);
}

/**
* 多文件上传
* @param files
* @return
* @throws IOException
*/
@PostMapping("/uploadMore")
public JsonResult uploadMore(MultipartFile[] files) throws IOException {
String uploadMore = UploadService.uploadMore(files, filesConfig.getTemporaryPath());
String[] uploadMores = uploadMore.split(",");
return ResponseResult.Success(ResultCodeEnums.SUCCESS,uploadMores);
}

/**
* 文件转移:适用于多文件以及单文件
* @param uploadPath
* @return
* @throws IOException
*/
@PostMapping("/change")
public JsonResult filesChange(@RequestBody String [] uploadPath) throws IOException {
//循环遍历传来的String数组
for (String u : uploadPath) {
//拿到临时目录的文件
String path = filesConfig.getTemporaryPath() + u;
File file = new File(path);
//File类型转换为MultipartFile类型
MultipartFile multipartFile = new MockMultipartFile(file.getName(), new FileInputStream(file));
//正式目录名与文件名生成一个新的路径
String newPath = filesConfig.getFormalPath() + u;
File newFile = new File(newPath);
//判断文件目录是否存在
if (!newFile.getParentFile().exists()) {
//创建文件存放目录
//无论是几个/,都是创建一个文件夹
//mkdirs(): 创建多层目录,如:E:/upload/2019
//mkdir(): 只创建一层目录,如:E:upload
//如果不加这一行不会创建新的文件夹,会报系统找不到路径
newFile.getParentFile().mkdirs();
}
//存储文件
multipartFile.transferTo(newFile);
//去掉目录名,保留文件总体路径,通过该路径访问图片
}
return ResponseResult.Success(ResultCodeEnums.SUCCESS);
}
}

文件过大异常捕获

/**
* @Author Qin
* @Date 2019-03-13 11:46
*/
@RestControllerAdvice
public class MyExceptionHandler {

@Autowired
private FilesConfig filesConfig;

/**
* 文件上传过大返回异常信息
* @param e
* @return
*/
@ExceptionHandler(MaxUploadSizeExceededException.class)
public JsonResult handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
String message = ResultCodeEnums.FAIL_10006.msg()
.replace("${size}",filesConfig.getMaxFileSize())
.replace("${allsize}",filesConfig.getMaxRequestSize());
ResultCodeEnums.FAIL_10006.setMsg(message);
return ResponseResult.Fail(ResultCodeEnums.FAIL_10006);//FAIL_10006("10006","单文件最大不可以超过${size},多文件最大不可以超过${allsize}"),
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: