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

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




    }
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java读取OSS文件并替换的示例代码: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class OSSFileReader { private static final String endpoint = "oss-cn-hangzhou.aliyuncs.com"; private static final String accessKeyId = "yourAccessKeyId"; private static final String accessKeySecret = "yourAccessKeySecret"; private static final String bucketName = "yourBucketName"; private static final String objectName = "yourObjectName"; public static void main(String[] args) throws IOException { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); InputStream inputStream = ossClient.getObject(bucketName, objectName).getObjectContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); // 读取文件内容并存储到List中 List<String> contentList = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { contentList.add(line); } // 替换文件内容 for (int i = 0; i < contentList.size(); i++) { String content = contentList.get(i); if (content.contains("oldValue")) { contentList.set(i, content.replace("oldValue", "newValue")); } } // 上传更新后的文件 StringBuilder stringBuilder = new StringBuilder(); for (String content : contentList) { stringBuilder.append(content).append("\n"); } ossClient.putObject(bucketName, objectName, stringBuilder.toString().getBytes()); ossClient.shutdown(); } } ``` 该代码使用阿里云Java SDK访问OSS服务,首先读取指定的文件内容并存储到List中,然后遍历List,将需要替换的内容进行替换,最后将更新后的内容上传到OSS。注意,这里只是简单的示例代码,实际应用中可能需要根据实际情况进行优化和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值