OssUtils.java 15.7 KB
package com.lhcredit.common.utils;


import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/web/upLoadFile")
public class OssUtils {
    private static String ossUrl = "http://101.200.76.6:8085";
//   private static String ossUrl="http://localhost:8095";



    /**
     *
     * @param file     上传文件
     * @param useOriginalFilename  是否使用原文件名
     * @param noRestrict    是否无限制附件类型
     * @return
     */
    @PostMapping
    public AnnexInfo uploadFile(MultipartFile file, String useOriginalFilename,String  noRestrict) {
        if (null==file)return AnnexInfo.builder().code(5000).msg("文件为空").build();
        useOriginalFilename=StringUtils.isEmpty(useOriginalFilename)?"false":"true";
        noRestrict=StringUtils.isEmpty(noRestrict)?"false":"true";
        String post = POST(ossUrl + "/oss/standardAnnax", null, file, file.getOriginalFilename(), noRestrict, useOriginalFilename);
        AnnexInfo annexInfo = JSONObject.parseObject(post, AnnexInfo.class);
        return annexInfo;
    }
    @RequestMapping("downloadUrl")
    public void downloadUrl(String url, HttpServletResponse response) {
        downloadUrlForResponse(url,response);
    }
    /**
     * 本地测试  获取生成token
     */
    public static void main(String[] args) {
        System.out.println(getToken());
    }
    /**
     * 标准附件  格式受限"jpg","png","pdf","doc","txt","docx","xlsx","xls","ppt"
     */
    public static AnnexInfo standardAnnax(MultipartFile file) {
        try {
            String post = POST(ossUrl + "/oss/standardAnnax", null, file, file.getOriginalFilename(),"false","false");
            return JSONObject.parseObject(post, AnnexInfo.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static AnnexInfo standardAnnax2(MultipartFile file) {
        try {
//            String post = POST(ossUrl + "/oss/standardAnnax", null, file, file.getOriginalFilename(),"false","false");
//            return JSONObject.parseObject(post, AnnexInfo.class);
            JSONObject jsonObject = doPostFormData(ossUrl + "/oss/import", file.getOriginalFilename(), file, new HashMap<>());
            System.out.println(jsonObject.toJSONString());
            return new AnnexInfo();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 标准附件  格式受限"jpg","png","pdf","doc","txt","docx","xlsx","xls","ppt"
     */
    public static AnnexInfo standardAnnax(File file) {
        try {
            String post = POST(ossUrl + "/oss/standardAnnex", new FileInputStream(file), null, file.getName(),"false","false");
            return JSONObject.parseObject(post, AnnexInfo.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据 文件原名称上传 文件
     * @param multipartFile
     * @param file
     * @return
     */
    public static AnnexInfo  useOriginalFilename(MultipartFile multipartFile,File file){
        try {
            String post = POST(ossUrl + "/oss/useOriginalFilename", null!=file?new FileInputStream(file):null, null!=multipartFile?multipartFile:null,
                    null!=multipartFile?multipartFile.getOriginalFilename():file.getName(),"true","true");
            return JSONObject.parseObject(post, AnnexInfo.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 以post方式调用第三方接口,以form-data 形式  发送 MultipartFile 文件数据
     *
     * @param url           post请求url
     * @param fileParamName 文件参数名称
     * @param multipartFile 文件
     * @param paramMap      表单里其他参数
     * @return 响应结果
     */
    public static JSONObject doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, Object> paramMap) {
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            String fileName = multipartFile.getOriginalFilename();
            // 文件流
            builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            //表单中其他参数
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                builder.addPart(entry.getKey(), new StringBody((String) entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            httpPost.setHeader("token",getToken());
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String s = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                jsonResult = JSONObject.parseObject(s);
                return jsonResult;

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }




    private static String POST(String url, InputStream inputStream, MultipartFile multipartFile, String name,String noRestrict,String useOriginalFilename)   {
        String body = null;
        try {
            body = HttpRequest.post(url).timeout(900000)
                    .header("token",getToken())
                    .header("content-type","application/x-www-form-urlencoded")
                    .form("file", new InputStreamResource(null!=inputStream?inputStream:multipartFile.getInputStream(),name))
                    .form("noRestrict",noRestrict)
                    .form("useOriginalFilename",useOriginalFilename)
                    .execute().body();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return body;
    }

    private static String getToken() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(date);
       String token= "d5a672629059998e9e8b_" + AES.encrypt(dateStr);
        System.out.println(token);
        return token;
    }

    public static void downloadUrlForResponse(String fileURL, HttpServletResponse response) {
        OutputStream outputStream = null;
        InputStream in = null;
        try {
            // 创建URL对象
            URL url = new URL(fileURL);
            // 打开连接
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            httpConn.setRequestMethod("GET");
            // 获取响应码,200表示成功
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                in = httpConn.getInputStream();

                // 构建保存文件的路径
                String fileName = "";
                String disposition = httpConn.getHeaderField("Content-Disposition");
                String contentType = httpConn.getContentType();
                int contentLength = httpConn.getContentLength();
                if (disposition != null) {
                    // extracts file name from header field
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10,
                                disposition.length() - 1);
                    }
                } else {
                    // extracts file name from URL
                    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
                }
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                response.setContentType("application/octet-stream"); // 通用的二进制数据类型
                outputStream = response.getOutputStream();
                byte[] buffer = new byte[1024]; // 缓冲区大小,可以根据实际情况调整
                int bytesRead;
                // 循环读取输入流中的数据并写入到输出流
                while ((bytesRead = in.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                // 刷新输出流,确保所有缓冲的数据都已写出
                outputStream.flush();
                System.out.println("File downloaded successfully.");
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();

        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            try {
                outputStream.close();
                in.close();
            } catch (Exception e) {
            }
        }

    }

    public static void downloadFile(String fileURL, String saveDir) {
        try {
            // 创建URL对象
            URL url = new URL(fileURL);
            // 打开连接
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            httpConn.setRequestMethod("GET");
            // 获取响应码,200表示成功
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                InputStream in = httpConn.getInputStream();
                // 构建保存文件的路径
                String fileName = "";
                String disposition = httpConn.getHeaderField("Content-Disposition");
                String contentType = httpConn.getContentType();
                int contentLength = httpConn.getContentLength();

                if (disposition != null) {
                    // extracts file name from header field
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10,
                                disposition.length() - 1);
                    }
                } else {
                    // extracts file name from URL
                    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
                }

                // 构造保存文件的完整路径
                Path saveFilePath = Paths.get(saveDir, fileName);

                // 创建输出流
                try (OutputStream out = Files.newOutputStream(saveFilePath)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }
                System.out.println("File downloaded successfully.");
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();
        } catch (MalformedURLException e) {
            System.out.println("Error: Invalid URL " + fileURL);
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @Builder
    public static class AnnexInfo {
        private Integer code;
        private String msg;
        private String originalFilename;
        private String fileName;
        private String saveName;
        private String ex;
        private String url;
    }

    // AES加解密
    private static class AES {
        private static final String ALGORITHM = "AES";
        private static final byte[] keyValue = "Lhzx1234Lhzx1234".getBytes();

        public static String encrypt(String valueToEnc) {
            try {
                Key key = generateKey();
                Cipher c = Cipher.getInstance(ALGORITHM);
                c.init(Cipher.ENCRYPT_MODE, key);
                byte[] encValue = c.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8));
                // 可选地,对加密后的字节进行Base64编码以便于文本显示和传输
                String encryptedValue = Base64.getEncoder().encodeToString(encValue);
                return encryptedValue;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public static String decrypt(String encryptedValue) {
            try {
                Key key = generateKey();
                Cipher c = Cipher.getInstance(ALGORITHM);
                c.init(Cipher.DECRYPT_MODE, key);
                // 先将Base64编码的字符串解码回字节数组
                byte[] decordedValue = Base64.getDecoder().decode(encryptedValue);
                byte[] decValue = c.doFinal(decordedValue);
                String decryptedValue = new String(decValue, StandardCharsets.UTF_8);
                return decryptedValue;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        private static Key generateKey() {
            try {
                Key key = new SecretKeySpec(keyValue, ALGORITHM);
                return key;
            } catch (Exception e) {

            }
            return null;
        }
    }


}