FileUtil
将任意格式的文件上传,本文章以 svg文件举例。
注:文件名中不要有各种杂乱符号,否则会出错。
代码实现
import java.io.File;
import java.io.FileOutputStream;
/**
* @author NNroc
* @date 2020/6/17 22:27
*/
public class FileUtil {
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
}
FileUtil 使用方法
/**
* 上传图片
* @param svg svg文件
* @param manage 要保存在manage文件夹下
* @return
* @throws Exception
*/
@AdministratorToken
@RequestMapping("/send_pic")
public Result sendPic(MultipartFile svg, @RequestParam String manage) throws Exception {
// 判断用户是否上传了文件
if (!svg.isEmpty()) {
// 文件上传的地址
String path = getJarRoot() + "/svg/" + manage + "/";
// 当前路径:G:\githubuse\internally\target
if (!Files.exists(Paths.get(path))) {
Files.createDirectories(Paths.get(path));
}
// 获取文件的名称
String fileName = svg.getOriginalFilename();
// 限制文件上传的类型
String contentType = svg.getContentType();
if ("image/svg+xml".equals(contentType)) {
// 完成文件的上传
FileUtil.uploadFile(svg.getBytes(), path, fileName);
return responseData.write("上传成功!", 200, new HashMap<>());
} else {
return responseData.write("文件非svg形式!", 400, new HashMap<>());
}
}
return responseData.write("上传失败!", 404, new HashMap<>());
}