You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
spring-boot-online-exam/backend/src/main/java/lsgwr/exam/utils/FileTransUtil.java

154 lines
5.8 KiB

package lsgwr.exam.utils;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/***********************************************************
* @note : 文件传输工具类
* @author : 梁山广
* @version : V1.0 at 2019/5/19 16:15
***********************************************************/
@Slf4j
public class FileTransUtil {
/**
* 上传单个文件
*
* @param uploadfile 上传的文件
* @param dir 文件要保存的文件夹
* @return 成功或者失败消息
*/
public static String uploadFile(MultipartFile uploadfile, String dir) {
log.info("Single file upload!");
if (uploadfile.isEmpty()) {
return "文件名不能为空";
}
try {
saveUploadedFiles(Arrays.asList(uploadfile), dir);
} catch (IOException e) {
e.printStackTrace();
return "后台服务异常";
}
log.info("file upload successfully! " + dir);
return "文件上传成功";
}
/**
* 多文件上传
*
* @param uploadfiles 要上传的多个文件
* @param dir 要保存的目录
* @return 成功或者失败消息
*/
public static String uploadFiles(MultipartFile[] uploadfiles, String dir) {
// 打印调试信息
log.debug("Multiple file upload!");
// 将上传的文件名拼接成一个字符串
String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename()).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
// 如果文件名为空,则返回错误信息
if (StringUtils.isEmpty(uploadedFileName)) {
return "文件名不能为空";
}
try {
// 调用工具类保存上传的文件
FileTransUtil.saveUploadedFiles(Arrays.asList(uploadfiles), dir);
} catch (IOException e) {
// 如果保存文件时发生异常,则返回错误信息
return "后台服务异常";
}
// 打印上传成功的日志信息
log.info("file upload successfully! " + uploadedFileName);
// 返回上传成功的提示信息
return "文件上传成功";
}
/**
* 保存文件到指定路径
*
* @param files 上传的文件
* @throws IOException 文件保存异常
*/
// 保存上传的文件
public static void saveUploadedFiles(List<MultipartFile> files, String dir) throws IOException {
// 遍历文件列表
for (MultipartFile file : files) {
// 如果文件为空,则跳过
if (file.isEmpty()) {
continue;
}
// 如果文件夹不存在,则创建
if (!FileUtil.exist(dir)) {
// 文件夹不存在就创建
FileUtil.mkdir(dir);
}
// 获取文件的字节数组
byte[] bytes = file.getBytes();
// 获取文件的原始文件名,并替换反斜杠为正斜杠
String fileName = file.getOriginalFilename().replace("\\", "/");
// 如果文件名中包含斜杠,则说明是上传文件夹
if (fileName.lastIndexOf('/')>0){
// 上传文件夹的时候会有这种情况
// 获取文件夹路径
String fileDir = dir + "/" + fileName.substring(0, fileName.lastIndexOf('/'));
// 如果文件夹不存在,则创建
if (!FileUtil.exist(fileDir)) {
// 文件夹不存在就创建,创建文件夹的时候会用到
FileUtil.mkdir(fileDir);
}
}
// 获取文件的路径
Path path = Paths.get(dir + "/" + fileName);
// 将文件写入路径
Files.write(path, bytes);
}
}
/**
* 根据文件路径下载文件
*
* @param filePath 要现在的文件的路径
* @return 文件流
* @throws IOException 文件流读取异常
*/
public static ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
// 记录下载文件的信息
log.info("downloading file : " + filePath);
// 创建文件系统资源
FileSystemResource file = new FileSystemResource(filePath);
// 创建响应头
HttpHeaders headers = new HttpHeaders();
// 设置缓存控制
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
// 设置文件下载时的文件名
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(file.getFilename().getBytes("gbk"), "iso-8859-1")));
// 设置缓存控制
headers.add("Pragma", "no-cache");
// 设置缓存控制
headers.add("Expires", "0");
// 打印文件名
System.out.println(file.getFilename());
// 返回响应实体
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
}