外网获取内网阿里云oss文件的一个方法

最近做wps相关功能,然后wps获取的文件必须放在公网上,但是为了保密行,oss文件服务器必须为内网,所以经过多方思考项出了一个方发。

首先获取一个下载连接

String url="https://foo.bar.com/files/9/180";   //文件地址
String dowUrl=address+":/vs/3rd/oss?ossUrl="+url;   //address本机地址(如果是服务器,写服务器地址如:10.169.145.191:8080/
return dowUrl;//把这个地址返回

访问地址,返回的地址dowUrl在下载的时候会从新访问了下面的接口

@RequestMapping(value="/vs/3rd/oss",method = {RequestMethod.GET})
public void getOss(@RequestParam("ossUrl") String ossUrl, HttpServletResponse response){
     previewService.getOss(ossUrl,response);
}

service 

public void getOss(String ossUrl, HttpServletResponse response) {
 try{
        URL url = new URL(ossUrl);
        int i = ossUrl.lastIndexOf("?Expires");
        int i1 = ossUrl.lastIndexOf(".");
        String substring = ossUrl.substring(i1 , i);
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();//截取文件名称
        String substring1 = ossUrl.substring(0, i);//先截取?前面的
            int i2 = substring1.lastIndexOf("/");//在截取最后一个/


        FileInputStream filein = FileUtil.convertInputStreamToFileInputStream(in,substring);
        byte[] buffer = new byte[filein.available()];
        filein.read(buffer);
        filein.close();
        // 清空response
        response.reset();
        // 设置response的Header
        
          response.addHeader("Content-Disposition", "attachment;"+substring1.substring(i2+1,i));

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");//注意 wps需要的格式为(application/msword)
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}

import java.io.*;

/**
 * 功能描述:
 */

public class FileUtil {

    public static FileInputStream convertInputStreamToFileInputStream(InputStream inputStream, String houzui) throws IOException {
        // 使用Java的File类创建一个临时文件
        File tempFile = File.createTempFile("temp", houzui);

        // 使用IO流将inputstream写入临时文件
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.flush();
        }

        // 将临时文件转换为fileinputstream
        FileInputStream fileInputStream = new FileInputStream(tempFile);
        return fileInputStream;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值