FileSysUtils.java 6.49 KB
package com.lhcredit.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
public class FileSysUtils {
    public static String host = "http://filestorage.lhdna.com";
//    public static String host = "http://localhost:8050";
    private static DirectoryType directoryType = DirectoryType.creditManager;


    public static void main(String[] args) {
        System.out.println(FileSysUtils.upLoadFile(new File("C:\\Users\\HASEE\\Desktop\\中国商业信用评价平台操作手册.pdf")));
    }



    public enum DirectoryType {
        Public("0","public"),
        media("1","media"),
        report("2","reportSys"),
        creditManager("3","creditManager"),
        zhengCe("4","zhengCe"),
        ;
        public String directory;
        public String name;

        DirectoryType(String directorm,String name) {
            this.directory = directorm;
            this.name = name;
        }
        public static DirectoryType getDirectoryType(String directory) {
            if (directory == null) {
                return DirectoryType.Public;
            }
            for (DirectoryType directoryType : DirectoryType.values()) {
                if (directoryType.directory.equals(directory)) {
                    return directoryType;
                }
            }
            return DirectoryType.Public;
        }
    }



    public static void download(String path, HttpServletResponse response, String fileName) {
        try {
            path = path.replace("/group", "");
            downloadFileToResponse(host + "/" + path, response, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] downloadFile(String fileUrl, HttpServletResponse response) throws IOException{
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");
        int responseCode = httpConn.getResponseCode();
        ByteArrayOutputStream bais = new ByteArrayOutputStream();
        if (responseCode == HttpURLConnection.HTTP_OK) {
             try (InputStream inputStream = httpConn.getInputStream()) {
                 byte[] buffer = new byte[4096];
                 int bytesRead;
                 while ((bytesRead = inputStream.read(buffer)) != -1) {
                     bais.write(buffer, 0, bytesRead);
                 }
             }
        } else {
            throw new IOException("Server returned non-OK status: " + responseCode);
        }
        return bais.toByteArray();
    }

    public static void downloadFileToResponse(String fileUrl, HttpServletResponse response, String fileName) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");

        int responseCode = httpConn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 获取文件名
            String disposition = httpConn.getHeaderField("Content-Disposition");
            if (StringUtils.isEmpty(fileName)) {
                if (disposition != null) {
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10, disposition.length() - 1);
                    }
                } else {
                    fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                }
            }
            // 设置响应头
            response.setContentType(httpConn.getContentType());
            response.setContentLength(httpConn.getContentLength());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()) + "\"");
            // 写入文件内容到响应
            try (InputStream inputStream = httpConn.getInputStream();
                 OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } else {
            throw new IOException("Server returned non-OK status: " + responseCode);
        }
    }

    public static  String getFullPath(String str){
        if (StringUtils.isEmpty(str)){
            return null;
        }
        return host+"/"+str;
    }
    public String getPath(String str) {
        if (StringUtils.isEmpty(str) || !str.contains("\"code\":2000")) {
            return null;
        }
        String[] split = str.split("\"data\":\"");
        return split[1].replaceAll("\"}", "");
    }

    public static String upLoad(MultipartFile file) {
        try {
            String s = upLoadFile(file.getInputStream(), file.getOriginalFilename(), directoryType.directory);

            return new FileSysUtils().getPath(s);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String upLoadFile(File file) {
        String s = null;
        try {
            s = upLoadFile(new FileInputStream(file), file.getName(), directoryType.directory);
            System.out.println(s);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        return new FileSysUtils().getPath(s);
    }

    private static InputStreamResource getInputStream(InputStream file) {
        InputStreamResource isr = null;
        try {
            isr = new InputStreamResource(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isr;
    }
    public static String upLoadFile(InputStream inputStream, String fileName, String dir) {
        try {
            String file = HttpRequest.post(host + "/upLoad?directory=" + dir).form("file", new InputStreamResource(inputStream,fileName)).execute().body();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}