栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合OSS文件服务器(文件上传、下载及在线地址)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合OSS文件服务器(文件上传、下载及在线地址)

pom引入依赖包

		
        
            com.aliyun.oss
            aliyun-sdk-oss
            3.8.0
        

阿里云OSS配置(yml)

#阿里云oss
aliyun:
  endpoint: http://oss-cn-beijing.aliyuncs.com  # oss对外服务的访问域名
  access-key-id: *****njArc******3s # 访问身份验证中用到用户标识
  access-key-secret: *******WB9**** # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
  bucket: *** #桶名(文件目录)
  dir:

工具类,复制即用

@Slf4j
@Configuration
@PropertySource("classpath:/application.yml")
@Component
public class AliOssCloudUtil {

    @Value("${aliyun.endpoint:#{null}}")
    private String endpoint;

    @Value("${aliyun.access-key-id:#{null}}")
    private String accessKeyId;

    @Value("${aliyun.access-key-secret:#{null}}")
    private String accessKeySecret;

    @Value("${aliyun.bucket:#{null}}")
    private String bucketName;

    @Value("${aliyun.dir:#{null}}")
    private String dir;


    public String getDir() {
        return dir;
    }

    
    public OSS getOSSClient(){
        return new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
    }


    
    public String uploadFile2OSS(InputStream instream, String fileName) {
        OSS ossClient = getOSSClient();
        String ret = "";
        // 判断bucket是否已经存在,不存在进行创建
        if (!doesBucketExist(ossClient)) {
            createBucket(ossClient);
        }
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            // 指定上传文件操作时是否覆盖同名Object。
            // 不指定x-oss-forbid-overwrite时,默认覆盖同名Object。
            // 指定x-oss-forbid-overwrite为false时,表示允许覆盖同名Object。
            // 指定x-oss-forbid-overwrite为true时,表示禁止覆盖同名Object,如果同名Object已存在,程序将报错。
            objectMetadata.setHeader("x-oss-forbid-overwrite", "false");
            String objectName = dir + fileName;

            //上传文件
            ossClient.putObject(bucketName, objectName, instream, objectMetadata);
            // 设置URL过期时间(7天)
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24 * 7);
            URL url = ossClient.generatePresignedUrl(bucketName, objectName,expiration);
            log.info(objectName);
            ret = url.toString().split("\?")[0];
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    
    public String getOnlineAddress(String objectName,Date expiration){
        OSS ossClient = getOSSClient();
        String ret = null;
        try {
            URL url = ossClient.generatePresignedUrl(bucketName, objectName,expiration);
            ret = url.toString().split("\?")[0];
        } catch (ClientException e) {
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        return ret;
    }


    
    public boolean doesObjectExist(OSS ossClient,String objectName) {
        boolean exists = ossClient.doesObjectExist(bucketName, dir + objectName);
        return exists;
    }

    
    public boolean doesBucketExist(OSS ossClient) {
        boolean exists = ossClient.doesBucketExist(bucketName);
        return exists;
    }

    
    public void createBucket(OSS ossClient) {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        // 设置bucket权限为公共读,默认是私有读写
        createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
        // 设置bucket存储类型为低频访问类型,默认是标准类型
        createBucketRequest.setStorageClass(StorageClass.IA);
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            try {
                ossClient.createBucket(createBucketRequest);
                // 关闭client
//                ossClient.shutdown();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    
    public static String getcontentType(String FilenameExtension) {
        if ("bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if ("jpeg".equalsIgnoreCase(FilenameExtension) ||
                "jpg".equalsIgnoreCase(FilenameExtension) ||
                "png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpeg";
        }
        if ("html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if ("pptx".equalsIgnoreCase(FilenameExtension) ||
                "ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if ("docx".equalsIgnoreCase(FilenameExtension) ||
                "doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpeg";
    }


    
    public void downloadFile(HttpServletResponse response, String objectName, String localFileName){
        // 创建OSSClient实例。
        OSS ossClient = getOSSClient();
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 读去Object内容  返回
            BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());

            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, "utf-8"));
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\a.txt")));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);

            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }

    
    public void downForZip( HttpServletResponse response,List filePath,String fileName){
        // 创建临时文件
        File zipFile = null;
        try {
            zipFile = File.createTempFile("test", ".zip");

            FileOutputStream f = new FileOutputStream(zipFile);
            
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            // 用于将数据压缩成Zip文件格式
            ZipOutputStream zos = new ZipOutputStream(csum);
            OSS ossClient=  getOSSClient();
            for (String ossFile : filePath) {
                // 获取Object,返回结果为OSSObject对象

                OSSObject ossObject = ossClient.getObject(bucketName, ossFile);
                // 读去Object内容  返回
                InputStream inputStream = ossObject.getObjectContent();
                // 对于每一个要被存放到压缩包的文件,都必须调用ZipOutputStream对象的putNextEntry()方法,确保压缩包里面文件不同名
                String name=ossFile.substring(ossFile.lastIndexOf("/")+1);
                zos.putNextEntry(new ZipEntry(name));
                int bytesRead = 0;
                // 向压缩文件中输出数据
                while ((bytesRead = inputStream.read()) != -1) {
                    zos.write(bytesRead);
                }
                inputStream.close();
                zos.closeEntry(); // 当前文件写完,定位为写入下一条项目
            }
            zos.close();
            response.reset();
            response.setContentType("text/plain");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Location", fileName);
            response.setHeader("Cache-Control", "max-age=0");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] car = new byte[1024];
            int l = 0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            // 关闭流
            fis.close();
            buff.close();
            out.close();

            ossClient.shutdown();
            // 删除临时文件
            zipFile.delete();
        }  catch (IOException e1) {
            e1.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }



}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/964208.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号