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

  • Post author:
  • Post category:其他


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);
        }




    }



版权声明:本文为qq_42892856原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。