xieb
2024-04-25 41dc2ca8393e40e9efb8a6bf05f2ab1400d80215
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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();
        }
    }
}