xieb
2024-04-11 f45ebeed1eb31505f7fd36f03050cb09a4319b90
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 com.dji.sample.patches.config.pojo.PatchesConfigPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 tmpFileDir = null;
        // 创建临时文件
        String randomFileName = UUID.randomUUID().toString();
        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);
        }
        ZipUtil.deleteFiles(tmpFileDir);
        return file;
    }
 
    //File转MultiparFile
    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;
    }
 
}