Prechádzať zdrojové kódy

添加阿里云存储

JX.Li 1 rok pred
rodič
commit
23346051a5

+ 9 - 0
ruoyi-admin/src/main/resources/application-dev.yml

@@ -180,3 +180,12 @@ sms:
     sdkAppId: appid
     #地域信息默认为 ap-guangzhou 如无特殊改变可不用设置
     territory: ap-guangzhou
+huawei:
+  obs:
+    ak: KZVKAAUQENCKITHZ3EWO
+    sk: B7tLa82CJ5EdNOh5a2G9i77sPYh8skcydTk3C8sb
+    upload:
+      endPoint: obs.cn-north-4.myhuaweicloud.com
+    access:
+      endPoint: https://szrqgz1.obs.cn-north-4.myhuaweicloud.com
+    bucketName: szrqgz1

+ 9 - 0
ruoyi-admin/src/main/resources/application-prod.yml

@@ -183,3 +183,12 @@ sms:
     sdkAppId: appid
     #地域信息默认为 ap-guangzhou 如无特殊改变可不用设置
     territory: ap-guangzhou
+huawei:
+  obs:
+    ak: KZVKAAUQENCKITHZ3EWO
+    sk: B7tLa82CJ5EdNOh5a2G9i77sPYh8skcydTk3C8sb
+    upload:
+      endPoint: obs.cn-north-4.myhuaweicloud.com
+    access:
+      endPoint: https://szrqgz1.obs.cn-north-4.myhuaweicloud.com
+    bucketName: szrqgz1

+ 5 - 1
ruoyi-framework/pom.xml

@@ -66,7 +66,11 @@
             <groupId>com.ruoyi</groupId>
             <artifactId>ruoyi-common</artifactId>
         </dependency>
-
+        <dependency>
+            <groupId>com.huaweicloud</groupId>
+            <artifactId>esdk-obs-java-bundle</artifactId>
+            <version>[3.21.8,)</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 194 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/obs/FileUtil.java

@@ -0,0 +1,194 @@
+package com.ruoyi.framework.obs;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLEncoder;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;
+
+@Slf4j
+public class FileUtil {
+
+    /**
+     * 压缩文件夹https://www.cnblogs.com/zeng1994/p/7862288.html
+     *
+     * @param srcDir           要压缩的文件夹路径
+     * @param out
+     * @param KeepDirStructure true
+     * @throws RuntimeException
+     */
+    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
+
+        long start = System.currentTimeMillis();
+
+        ZipOutputStream zos = null;
+        File sourceFile = null;
+        try {
+
+            zos = new ZipOutputStream(out);
+            sourceFile = new File(srcDir);
+            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
+            long end = System.currentTimeMillis();
+            System.out.println("压缩完成,耗时:{}ms" + (end - start));
+        } catch (Exception e) {
+            log.warn("小区压缩文件打包util:"+e);
+            throw new RuntimeException("zip error from ZipUtils", e);
+        } finally {
+            if (zos != null) {
+                try {
+                    zos.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            // 删除压缩之前的文件夹
+            if (sourceFile != null) {
+//                log.info("正在删除原文件");
+//                deleteFolder(sourceFile);
+            }
+        }
+    }
+
+
+    /**
+     * 设置导出zip的响应格式
+     *
+     * @param request
+     * @param response
+     * @param fileZip  zip的名字
+     * @param filePath zip的路径
+     * @throws UnsupportedEncodingException
+     */
+    public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, String fileZip, String filePath) throws UnsupportedEncodingException {
+
+        //进行浏览器下载
+        final String userAgent = request.getHeader("USER-AGENT");
+        //判断浏览器代理并分别设置响应给浏览器的编码格式
+        String finalFileName = null;
+        if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
+            // IE浏览器
+            finalFileName = URLEncoder.encode(fileZip, "UTF8");
+            System.out.println("IE浏览器");
+        } else if (StringUtils.contains(userAgent, "Mozilla")) {
+            // google,火狐浏览器
+            finalFileName = new String(fileZip.getBytes(), "ISO8859-1");
+        } else {
+            // 其他浏览器
+            finalFileName = URLEncoder.encode(fileZip, "UTF8");
+        }
+        // 告知浏览器下载文件,而不是直接打开,浏览器默认为打开
+        response.setContentType("application/x-download");
+        // 下载文件的名称
+        response.setHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");
+
+        ServletOutputStream servletOutputStream = null;
+        try {
+            servletOutputStream = response.getOutputStream();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        DataOutputStream temps = new DataOutputStream(
+                servletOutputStream);
+        // 浏览器下载文件的路径
+        DataInputStream in = null;
+        try {
+            in = new DataInputStream(
+                    new FileInputStream(filePath));
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        }
+        byte[] b = new byte[2048];
+        // 之后用来删除临时压缩文件
+        File reportZip = new File(filePath);
+        try {
+            while ((in.read(b)) != -1) {
+                temps.write(b);
+            }
+            temps.flush();
+        } catch (Exception e) {
+            e.printStackTrace();
+            log.warn("下载小区压缩文件util:"+e);
+        } finally {
+            if (temps != null) {
+                try {
+                    temps.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if (reportZip != null) {
+                // 删除服务器本地产生的临时压缩文件!
+                reportZip.delete();
+            }
+            try {
+                servletOutputStream.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    /**
+     * 递归压缩方法
+     *
+     * @param sourceFile       源文件
+     * @param zos              zip输出流
+     * @param name             压缩后的名称
+     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
+     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
+     * @throws Exception
+     */
+    private static void compress(File sourceFile, ZipOutputStream zos, String name,
+                                 boolean KeepDirStructure) throws Exception {
+        byte[] buf = new byte[BUFFER_SIZE];
+        if (sourceFile.isFile()) {
+            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
+            zos.putNextEntry(new ZipEntry(name));
+            // copy文件到zip输出流中
+            int len;
+            FileInputStream in = new FileInputStream(sourceFile);
+            while ((len = in.read(buf)) != -1) {
+                zos.write(buf, 0, len);
+            }
+            // Complete the entry
+            zos.closeEntry();
+            in.close();
+        } else {
+            File[] listFiles = sourceFile.listFiles();
+            if (listFiles == null || listFiles.length == 0) {
+                // 需要保留原来的文件结构时,需要对空文件夹进行处理
+                if (KeepDirStructure) {
+                    // 空文件夹的处理
+                    zos.putNextEntry(new ZipEntry(name + "/"));
+                    // 没有文件,不需要文件的copy
+                    zos.closeEntry();
+                }
+            } else {
+                for (File file : listFiles) {
+                    // 判断是否需要保留原来的文件结构
+                    if (KeepDirStructure) {
+                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
+                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
+                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
+                    } else {
+                        compress(file, zos, file.getName(), KeepDirStructure);
+                    }
+                }
+            }
+        }
+    }
+}

+ 163 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/obs/ObsService.java

@@ -0,0 +1,163 @@
+package com.ruoyi.framework.obs;
+
+import cn.hutool.core.util.IdUtil;
+import com.obs.services.ObsClient;
+import com.obs.services.ObsConfiguration;
+import com.obs.services.exception.ObsException;
+import com.obs.services.model.ObsObject;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.WritableByteChannel;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Component
+public class ObsService {
+
+    @Value("${huawei.obs.ak}")
+    private String ak;
+
+    @Value("${huawei.obs.sk}")
+    private String sk;
+
+    @Value("${huawei.obs.upload.endPoint}")
+    private String endPoint;
+
+    @Value("${huawei.obs.bucketName}")
+    private String bucketName;
+
+    @Value("${huawei.obs.access.endPoint}")
+    private String accessEndPoint;
+
+    private final String objectKey = "file/";
+
+    //objectKey就是文件名,如果桶中有文件夹的话,如往test文件上传test.txt文件,那么objectKey就是test/test.txt
+    public Map<String, Object> uploadFile(MultipartFile file) throws Exception {
+        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
+        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
+        String fileName = IdUtil.fastSimpleUUID() + "." + suffix;
+        InputStream inputStream = file.getInputStream();
+        obsClient.putObject(bucketName, objectKey + fileName, inputStream);
+        inputStream.close();
+        obsClient.close();
+        Map map = new HashMap();
+        map.put("url", accessEndPoint + "/" + objectKey + fileName);
+        map.put("objectKey", objectKey + fileName);
+        return map;
+    }
+
+    @Async
+    public void deleteFiles(List<String> list) {
+        list.forEach(x -> {
+            try {
+                deleteFile(objectKey + x.substring(x.lastIndexOf("/") + 1));
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        });
+    }
+
+    public void deleteFile(String objectKey) throws Exception {
+        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
+        obsClient.deleteObject(bucketName, objectKey);
+        obsClient.close();
+    }
+
+    public void download(String localFilePath, String fileName) throws ObsException, IOException {
+        ObsConfiguration config = new ObsConfiguration();
+        config.setSocketTimeout(30000);
+        config.setConnectionTimeout(10000);
+        config.setEndPoint(endPoint);
+        ObsClient obsClient = null;
+        try {
+            obsClient = new ObsClient(ak, sk, config);
+            System.out.println("Create a new bucket for demo\n");
+//            obsClient.createBucket(bucketName);
+            System.out.println("Uploading a new object to OBS from a file\n");
+//            obsClient.putObject(bucketName, objectKey, createSampleFile());
+            System.out.println("Downloading an object\n");
+            simpleDownload(obsClient);
+            File localFile = new File(localFilePath);
+            if (!localFile.getParentFile().exists()) {
+                localFile.getParentFile().mkdirs();
+            }
+            System.out.println("Downloading an object to file:" + localFilePath + "\n");
+            downloadToLocalFile(obsClient, localFilePath, fileName);
+            System.out.println("Deleting object  " + objectKey + "\n");
+//            obsClient.deleteObject(bucketName, objectKey, null);
+
+        } catch (ObsException e) {
+            System.out.println("Response Code: " + e.getResponseCode());
+            System.out.println("Error Message: " + e.getErrorMessage());
+            System.out.println("Error Code:       " + e.getErrorCode());
+            System.out.println("Request ID:      " + e.getErrorRequestId());
+            System.out.println("Host ID:           " + e.getErrorHostId());
+        } finally {
+            if (obsClient != null) {
+                try {
+                    /*
+                     * Close obs client
+                     */
+                    obsClient.close();
+                } catch (IOException e) {
+                }
+            }
+        }
+    }
+
+    private void simpleDownload(ObsClient obsClient) throws ObsException, IOException {
+        ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
+        displayTextInputStream(obsObject.getObjectContent());
+    }
+
+    private void displayTextInputStream(InputStream input) throws IOException {
+        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
+        while (true) {
+            String line = reader.readLine();
+            if (line == null)
+                break;
+
+            System.out.println("\t" + line);
+        }
+        System.out.println();
+
+        reader.close();
+    }
+
+    private void downloadToLocalFile(ObsClient obsClient, String localFilePath, String fileName) throws ObsException, IOException {
+        String key = objectKey + fileName;
+        ObsObject obsObject = obsClient.getObject(bucketName, key, null);
+        ReadableByteChannel rchannel = Channels.newChannel(obsObject.getObjectContent());
+
+        ByteBuffer buffer = ByteBuffer.allocate(4096);
+        WritableByteChannel wchannel = Channels.newChannel(new FileOutputStream(new File(localFilePath + "/" + fileName)));
+
+        while (rchannel.read(buffer) != -1) {
+            buffer.flip();
+            wchannel.write(buffer);
+            buffer.clear();
+        }
+        rchannel.close();
+        wchannel.close();
+    }
+
+    private File createSampleFile() throws IOException {
+        File file = File.createTempFile("obs-java-sdk-", ".txt");
+        file.deleteOnExit();
+        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
+        writer.write("abcdefghijklmnopqrstuvwxyz\n");
+        writer.write("0123456789011234567890\n");
+        writer.close();
+
+        return file;
+    }
+
+}