阿里云oss上传下载

简单demo复制粘贴即可使用

package com.shie.idiThird.untils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.ResponseHeaderOverrides;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class OssUtil {

    private volatile static OSS ossClient;

    private volatile static OSSClientBuilder ossClientBuilder;

    private static String ENDPOINT = null;

    private static String ACCESSKEYID = null;

    private static String ACCESSKEYSECRET = null;

    private static String BUCKET = null;
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accesskeyid}")
    private String accesskeyid;
    @Value("${oss.accesskeysecret}")
    private String accesskeysecret;
    @Value("${oss.bucket}")
    private String bucket;

    @PostConstruct
    public void init() {
        ENDPOINT = endpoint;
        ACCESSKEYID = accesskeyid;
        ACCESSKEYSECRET = accesskeysecret;
        BUCKET = bucket;
    }

    public static OSS initOSSClient() {
        if (ossClient == null) {
            if (ossClient == null) {
                ossClient = initOSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
            }
        }
        return ossClient;
    }

    public static OSSClientBuilder initOSSClientBuilder() {
        if (ossClientBuilder == null) {
            if (ossClientBuilder == null) {
                ossClientBuilder = new OSSClientBuilder();
            }
        }
        return ossClientBuilder;
    }

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

        return "image/jpg";
    }

    /**
     * 根据文件所在路径上传文件
     * @param filePath   文件所在路径
     * @param downName   文件名(下载时显示名称)
     * @return
     */
    public static String upload(String filePath,String downName) {

        String fileName = null;
        String fileType = filePath.substring(filePath.lastIndexOf("."));    //文件类型
        fileName = UUID.randomUUID().toString() + "." + fileType;               //文件名
        try(FileInputStream fileInputStream = new FileInputStream(filePath)) {
            fileName = upload(fileInputStream, downName, fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }

    /**
     *
     * @param inputStream  文件流
     * @param originalFilename  下载时显示文件名
     * @param uuidFileName  新文件名
     * @return
     */
    public static String upload(InputStream inputStream, String originalFilename,String uuidFileName) {
        initOSSClient();
        uuidFileName = "idi" + "/" + uuidFileName;
        //设置下载时,文件名称为原文件名
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //显示文件名过滤特殊字符
        originalFilename = IDIStringUtil.filterSpecialChar(originalFilename,"\\,/,:,*,?,\",<,>,|");
        String type = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        originalFilename = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        objectMetadata.setContentDisposition("attachment;filename="+ UriUtils.encode(originalFilename,"UTF-8")+"." + type);
        ossClient.putObject(BUCKET,uuidFileName,inputStream,objectMetadata);
        return uuidFileName;
    }

    public static String getFileUrl(String fileName) {
        initOSSClient();
        // 获取下载链接
        Date expiration = new Date(new Date().getTime() + 24 * 3600l * 1000);
        //返回上传文件下载路径
        String url = ossClient.generatePresignedUrl(BUCKET, fileName, expiration).toString();
        log.info("文件下载地址为:{}", url);
        return url;
    }

    /**
     * 自定义下载文件名,下载oos文件
     * @param fileId   文件oos对应的id
     * @param showName 自定义名称(带后缀)
     * @return
     */
    public static String getFileUrl(String fileId, String showName) {
        initOSSClient();

        Date expiration = new Date(new Date().getTime() + 24 * 3600l * 1000);     //设置链接过期时间
        String type = fileId.substring(fileId.lastIndexOf(".")+1);  //截取文件类型
        showName = showName.substring(0, showName.lastIndexOf("."));          //截取文件名
        //指定OSS返回请求的content-disposition头。
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET, fileId);
        generatePresignedUrlRequest.setExpiration(expiration);
        ResponseHeaderOverrides responseHeaderOverrides = new ResponseHeaderOverrides();
        responseHeaderOverrides.setContentDisposition("attachment;filename="+ UriUtils.encode(showName,"UTF-8")+"." + type);
        generatePresignedUrlRequest.setResponseHeaders(responseHeaderOverrides);
        //返回oos文件下载路径
        String url = ossClient.generatePresignedUrl(generatePresignedUrlRequest).toString();
        log.info("文件下载地址为:{}", url);
        return url;
    }

    /**
     * 下载oos文件流
     * @param fileId     文件id
     * @param showName   文件显示名称
     * @param response
     * @throws IOException
     */
    public static void getFileOutputStream(String fileId, String showName, HttpServletResponse response){
        initOSSClient();
        OSSObject oosObject = ossClient.getObject(BUCKET, fileId);
        InputStream is = oosObject.getObjectContent();
        getFileOutputStream(showName, response, is);
    }


    public static void getFileOutputStream(String showName, HttpServletResponse response, InputStream is) {

        try {
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader(
                    "Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(showName, "UTF-8"));
            try (
                    BufferedInputStream bis = new BufferedInputStream(is);
                    // 输出流
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            ) {
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = bis.read(buff)) > 0) {
                    bos.write(buff, 0, len);
                }
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值