package com.dji.sample.patches.utils;
|
|
import org.springframework.mock.web.MockMultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import java.io.*;
|
import java.util.UUID;
|
|
public class MultipartFileTOFileUtil {
|
/**
|
* MultiparFile转File
|
* @param multipartFile
|
* @param unzipPath
|
* @return
|
*/
|
public static File multipartFile2File(MultipartFile multipartFile, String unzipPath) {
|
// 创建临时文件
|
String randomFileName = UUID.randomUUID().toString();
|
String tmpFileDir = unzipPath + randomFileName;
|
File file = new File(tmpFileDir);
|
InputStream inputStream = null;
|
FileOutputStream outputStream = null;
|
try {
|
// 获取文件输入流
|
inputStream = multipartFile.getInputStream();
|
if (!file.exists()) {
|
file.createNewFile();
|
}
|
// 创建输出流
|
outputStream = new FileOutputStream(file);
|
byte[] bytes = new byte[1024];
|
int len;
|
// 写入到创建的临时文件
|
while ((len = ((InputStream) inputStream).read(bytes)) > 0) {
|
outputStream.write(bytes, 0, len);
|
}
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
return file;
|
}
|
|
public static MultipartFile convert(File file) throws IOException {
|
FileInputStream input = new FileInputStream(file);
|
MultipartFile multipartFile = new MockMultipartFile("file",
|
file.getName(), "application/octet-stream", input);
|
return multipartFile;
|
}
|
/**
|
* 将文件转换为MultipartFile类型。
|
* @param file 需要转换的文件对象,不可为null。
|
* @throws IOException 如果在读取文件时发生错误,则抛出IOException。
|
*/
|
public static void deleteFile(File file) {
|
if (file.exists()) {
|
file.delete();
|
}
|
}
|
}
|