使用OSS上传文件并读取文件进行显示

本文介绍了如何在Spring Boot应用中使用阿里云OSS (Object Storage Service),包括依赖引入、工具类实现、配置文件详解、上传操作示例以及静态文件访问。重点展示了初始化OSS客户端、上传和下载文件的功能,并提供了一个前端展示文件的简单示例。
摘要由CSDN通过智能技术生成

1.导包

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>

2.oss工具类

package leyan.admin.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import leyan.admin.web.config.LyConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;

@Slf4j
@RequiredArgsConstructor
@Component
public class OssHelper {
    private final LyConfig lyConfig;

    private OSS oss;
    private String ossBucket;

    @PostConstruct
    public void init() {
        var ossConfig = lyConfig.getOss();
        if (StringUtils.isNoneBlank(ossConfig.getEndpoint(), ossConfig.getBucket(), ossConfig.getKeyId(), ossConfig.getKeySecret())) {
            oss = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getKeyId(), ossConfig.getKeySecret());
            ossBucket = ossConfig.getBucket();
        }
    }

    public boolean put(String ossKey, byte[] bytes) {
        if (oss == null) {
            return false;
        }
        while (ossKey.length() > 0 && ossKey.charAt(0) == '/') {
            ossKey = ossKey.substring(1);
        }
        oss.putObject(ossBucket, ossKey, new ByteArrayInputStream(bytes));
        return true;
    }

    public byte[] get(String ossKey) {
        if (oss == null) {
            return null;
        }
        var ossObject = oss.getObject(ossBucket, ossKey);
        if (ossObject != null) {
            try (var is = ossObject.getObjectContent()) {
                return is.readAllBytes();
            } catch (Exception e) {
                log.debug("ossHelper", e);
                return null;
            }
        }
        return null;
    }

    public boolean copy(String srcKey, String targetKey) {
        if (oss == null) {
            return false;
        }
        oss.copyObject(ossBucket, srcKey, ossBucket, targetKey);
        return true;
    }
}

3.oss静态读取账号 全局配置:

package leyan.admin.web.config;


import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
@EnableConfigurationProperties(LyConfig.class)
@ConfigurationProperties("leyan")
public class LyConfig {

    private OssConfig oss;

    @Getter
    @Setter
    public static class OssConfig {
        private String endpoint;
        private String bucket;
        private String keyId;
        private String keySecret;
    }
}

application.properties配置账号:

leyan.oss.endpoint=*****************
leyan.oss.bucket=**************
leyan.oss.keyid=*****************
leyan.oss.keysecret=************

4.上传需要配置的路径名称,以及文件解码工具类

   /**
     *上传oos类
     */
    public Map<String, String> uploadCnUserInvoice(String billingNo, byte[] bytes) {
        Map rsMap = new HashMap<String, String>();
        var putType = "error";
        var invoiceUrl = "";
        try {
            var now = LocalDateTime.now();
            var uploadRoot = "cn-user/invoice/" + DateTimeFormatter.ofPattern("yyyy-MM").format(now) + "/";
            var timeKey = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(now) + "-" + RandomStringUtils.randomAlphanumeric(6);
            var filename = billingNo + "-" + timeKey + ".pdf";

            boolean b = ossHelper.put(uploadRoot + filename, bytes);
            if (b) {
                putType = "success";
                invoiceUrl = uploadRoot + filename;
            }
        } catch (Exception e) {
            log.debug("upload image to oss", e);
        } finally {
            rsMap.put("putType", putType);
            rsMap.put("invoiceUrl", invoiceUrl);
            return rsMap;
        }
    }


    /**
     * 从输入流中获取字节数组
     *
     * @return
     * @throws IOException
     */
    public  byte[] urlToBytes(String urlStr) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(5 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos.toByteArray();
    }


5.上传使用示例:

      //根据电子发票路径 存到云路径上 返回
      orderLineDownBilling = q;
      String systemBillingAddress = q.getSystemBillingAddress();//金蝶云地址
      //根据http路径拿到字节数组
      byte[] bytes = visitorUtil.urlToBytes(systemBillingAddress);
      //把字节数组上传到oos
      Map<String, String> rsMap = visitorUtil.uploadCnUserInvoice(q.getInvoiceNumber(), bytes);//把发票号 和字节数组传过去
      String typeUrl = rsMap.get("invoiceUrl");//拿到上传 返回的路径
      orderLineDownBilling.setLyBillingAddress(typeUrl);//存储
      systemOrderMapper.addOrderLineDownBilling(orderLineDownBilling);

6.上传成功后,通过文件夹名称访问读取 并显示

示例:

    /**
     *  代码示例  通过oss获得路径 访问
     */
    @GetMapping("/cn-user/report-filef")
    @ResponseBody
    public void testSystemPdfShow(HttpServletResponse response) throws IOException {
        var ossPdfPath = "cn-user/report-file/1-11/-20211116085706-b4Vh2q.pdf";
        var bs = ossHelper.get(ossPdfPath);
        if (bs != null) {
            var out = response.getOutputStream();
            response.setContentType("application/pdf;charset=UTF-8");
            response.setContentLength(bs.length);
            out.write(bs);
        } else {
            response.setStatus(404);
        }
    }

实际使用:
前台:

     <span th:if="${ineorderbilling.lyBillingAddress}!=null">
    <a target="_blank"  href="javascript:void(0)" style="color: #02a7df" th:href="|${ineorderbilling.invoiceNumber}-invoice.html|">发票链接</a>
    </span>

后台:

    //查看发票详情 电子发票
    @GetMapping(value = {"/{url}-invoice"})//根据超链接导向
    public void   selectInvoiceInfo(@PathVariable String url, Model model, HttpSession session, HttpServletRequest request,HttpServletResponse response) throws IOException {
        String invoiceNum = url;
        String ossPdfPath = null;
        //根据发票号找到oos云路径
        OrderLineDownBilling orderLineDownBilling = userService.selectInvoiceInfo(invoiceNum);
        System.out.println(orderLineDownBilling.getLyBillingAddress());
        if (!orderLineDownBilling.getLyBillingAddress().equals("")){
            ossPdfPath=orderLineDownBilling.getLyBillingAddress();
        }
        var bs = ossHelper.get(ossPdfPath);
        if (bs != null) {
            var out = response.getOutputStream();
            //直接返回
            response.setContentType("application/pdf;charset=UTF-8");
            response.setContentLength(bs.length);

            out.write(bs);
        } else {
            response.setStatus(404);
        }




    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值