whycxzp
2021-04-15 e4e8380597b5abdd2ede656cf5291c5d760b1149
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
60
61
62
63
64
65
66
67
68
package com.whyc.util;
 
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ResourceUtils;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class FileUtils {
 
    public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
 
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }
 
    /**
     * 项目同级路径
     * @return
     */
    public static String getFilePath() {
        ApplicationHome ah = new ApplicationHome(FileUtils.class);
        File file = ah.getSource();
//        String projectDir = file.getParentFile().getAbsolutePath();
        String projectDir = file.getAbsolutePath();
        String dir = projectDir + File.separator + "upload"+File.separator;
        System.out.println(dir);
        return dir;
    }
 
 
    /**
     * 生成项目同级路径
     * @return
     * @throws FileNotFoundException
     */
    public static String getProjectPath(){
        //获取跟目录
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) {
            path = new File("");
        }
        //如果上传目录为/static/images/upload/,则可以如下获取
        File upload = new File(path.getAbsolutePath(), "static/upload/");
        if (!upload.exists()) {
            upload.mkdirs();
            //在开发测试模式时,得到地址为:{项目跟目录}/target/static/images/upload/
            //在打成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
        }
        return upload.toString()+File.separator;
    }
 
}