PageOfficeV6.0打开阿里云对象存储OSS上的文档

转载:打开阿里云对象存储OSS上的文档

注意

本文中展示的代码均为关键代码,复制粘贴到您的项目中,按照实际的情况,例如文档路径,用户名等做适当修改即可使用。

某些Web项目中的文档存储采用了云对象存储的方式,比如把Office文档全部保存在阿里云对象存储OSS中,如果需要调用PageOffice在线打开云存储中的Office文件,那么就需要使用二进制流方式打开。

首先,编写一个下载文件的后台方法读取云对象存储中的Office文件,比如:openStream;

然后,把此openStream方法的url地址传递给PageOfficeCtrl对象的webOpen的第一个参数即可打开;

最后,保存文件时,调用FileSaver对象的getFileBytes()或getFileStream()获取到文件二进制流并保存到云对象存储中。


后端代码

编写下载文件的后台方法读取云对象存储(比如:阿里云OSS)中的Office文件:openStream;
Java

@RequestMapping(value = "openStream", method = RequestMethod.GET)
public void Openstream(HttpServletRequest request, HttpServletResponse response) 
                      throws SQLException, ClassNotFoundException, IOException {String fileName = request.getParameter("filename");
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,例如exampledir/exampleobject.docx。Object完整路径中不能包含Bucket名称。
String objectName = "exampledir/" + fileName;

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

try {
    // 调用ossClient.getObject返回一个OSSObject实例,该实例包含文件内容及文件元信息。
    OSSObject ossObject = ossClient.getObject(bucketName, objectName);
    // 调用ossObject.getObjectContent获取文件输入流,可读取此输入流获取其内容。
    InputStream content = ossObject.getObjectContent();
    if (content != null) {
        
        byte[] buffer = new byte[4096];
        int fileSize = 0;
        int byteread = 0;

        response.reset();
        OutputStream outputStream = response.getOutputStream();

        while ((byteread = content.read(buffer)) != -1) {
            fileSize += byteread; //字节数 文件大小
            outputStream.write(buffer, 0, byteread);
        }

        // application/msword, application/x-excel, application/ms-powerpoint, application/pdf
        response.setContentType("application/msword"); 
        response.setHeader("Content-Disposition",
                "attachment; filename=down.doc"); //fileN应该是编码后的(utf-8)
        response.setContentLength(fileSize);

        outputStream.flush();
        outputStream.close();
        outputStream = null;

        // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
        content.close();
    }
} catch (OSSException oe) {
    System.out.println("Caught an OSSException, which means your request made it to OSS, "
            + "but was rejected with an error response for some reason.");
    System.out.println("Error Message:" + oe.getErrorMessage());
    System.out.println("Error Code:" + oe.getErrorCode());
    System.out.println("Request ID:" + oe.getRequestId());
    System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
    System.out.println("Caught an ClientException, which means the client encountered "
            + "a serious internal problem while trying to communicate with OSS, "
            + "such as not being able to access the network.");
    System.out.println("Error Message:" + ce.getMessage());
} finally {
    if (ossClient != null) {
        ossClient.shutdown();
    }
}

}
在后端编写代码调用webOpen方法打开文件之前给SaveFilePage属性赋值(设置好保存时由哪个地址接口负责接收处理控件上传的文件流);
Java

PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
poCtrl.setSaveFilePage("saveStream?filename=exampleobject.docx"); // 设置保存文件的接口地址
//webOpen的第一个参数支持能够输出下载文件的Url相对地址或者文件在服务器上的磁盘路径两种方式
//查看详细,请在本站搜索“PageOffice属性或方法中涉及到的URL路径或磁盘路径的说明”
poCtrl.webOpen("openStream?filename=exampleobject.docx", OpenModeType.docNormalEdit, "张佚名");//打开文件

注意

对PageOfficeCtrl对象的所有属性赋值或函数调用都必须在WebOpen方法调用之前执行,否则会不生效。

在SaveFilePage属性指向的地址接口saveStream中,创建FileSaver对象处理文件的保存工作。
Java

@RequestMapping("saveStream")
public void saveStream(HttpServletRequest request, HttpServletResponse response) 
                  throws ClassNotFoundException, FileNotFoundException, SQLException {
FileSaver fs = new FileSaver(request, response);String fileName = request.getParameter("filename");
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写Object完整路径,例如exampledir/exampleobject.docx。Object完整路径中不能包含Bucket名称。
String objectName = "exampledir/" + fileName;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

try {
    ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(fs.getFileBytes()));
} catch (OSSException oe) {
    System.out.println("Caught an OSSException, which means your request made it to OSS, "
            + "but was rejected with an error response for some reason.");
    System.out.println("Error Message:" + oe.getErrorMessage());
    System.out.println("Error Code:" + oe.getErrorCode());
    System.out.println("Request ID:" + oe.getRequestId());
    System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
    System.out.println("Caught an ClientException, which means the client encountered "
            + "a serious internal problem while trying to communicate with OSS, "
            + "such as not being able to access the network.");
    System.out.println("Error Message:" + ce.getMessage());
} finally {
    if (ossClient != null) {
        ossClient.shutdown();
    }
}

fs.close();
}
posted @ 2023-08-24 16:29  爱吃苹果皮  阅读(114)  评论(0编辑  收藏  举报