最近做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; } }