前言
最近有用到文件上传,所以了解了一下Spring中的MultipartFile,然后进行一个简单的记录
首先要在yml文件中进行配置
我们根据业务的不同,有可能是需要上传到项目路径下,也有可能是上传到系统磁盘中,我这边是利用接口的方式进行测试,还没来得及封装为工具类,大家先凑合看,希望为大家提供一些帮助~~
package com.komlin.project.api.controller;
import com.komlin.common.utils.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
/**
* Description:接口测试
* date: 2020/8/19 9:42
*
* @author mt
* @since JDK 1.8
*/
@Api(tags = "接口测试")
@RestController
@Slf4j
@RequestMapping("api/mtTest")
public class ApiMtTestController {
//图片存放的系统磁盘路径
private final static String SAVE_PATH = "C:\\pic\\";
//项目路径
private final static String FILE_SAVE_PREFIX = "static/sltimage";
/**
* 将文件放到指定目录下
* @param type 类型
* @return
*/
private static File getFile(int type) {
File file = null;
String filePath = null;
if (Objects.equals(type,1)) {
//上传到项目路径下
filePath = new String("src/main/resources/" + FILE_SAVE_PREFIX);
file = new File(filePath);
} else if (Objects.equals(type,2)) {
//上传到磁盘
filePath = new String(SAVE_PATH);
file = new File(filePath);
}
if (!file.exists()) {
file.mkdirs();
}
return file;
}
/**
* 判断文件是否为图片
*
* @param type
* @return
*/
private static boolean isImg(String type) {
if (StringUtils.isNotEmpty(type)) {
if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
return true;
}
}
return false;
}
/**
* 上传文件到指定目录
* @param file 文件
* @param pathType 路径类型 1 上传到项目路径下 2 上传到磁盘
* @param request
* @return
* @throws IOException
*/
@PostMapping("/save")
public String fileTest(@RequestParam("photo") MultipartFile file, Integer pathType,HttpServletRequest request) throws IOException {
if (file.isEmpty()) {
return "文件不能为空";
}
//文件大小
long size = file.getSize();
//文件的byte大小
byte[] bytes = file.getBytes();
//文件原名称
String fileName = file.getOriginalFilename();
//文件类型
String type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;
if (type == null) {
return "文件类型为空";
}
// 判断文件类型是否为图片
if (isImg(type)) {
//项目在容器中实际发布运行的根路径
String realPath = request.getSession().getServletContext().getRealPath("/");
//自定义的文件名称,避免文件名重复
String trueFileName = "komlin_pic_" + String.valueOf(System.currentTimeMillis()) + "." + type;
File fileDir = getFile(pathType);
File newFile = new File(fileDir.getAbsolutePath() + "/" + trueFileName);
file.transferTo(newFile);
return "文件成功上传到指定目录下";
}
return "不是图片类型";
}
}