zoukankan      html  css  js  c++  java
  • SAE java应用读写文件(TmpFS和Storage)

    近期不少java用户都在提sae读写本地文件的问题,在这里结合TmpFS和Storage服务说说java应用应该如何读写文件
    TmpFS是一个供应用临时读写的路径,但请求过后将被销毁。出于安全考虑,sae限制了应用对本地IO操作,但本地操作肯定是存在的,所以sae提供了TmpFS来应对。如果需要将文件持久化怎么办呢?当然是使用storage。

    下面给出一个例子结合storage和TmpFS来写文件
    首先使用common-upload将文件上传至TmpFS下,之后再使用SaeStorage对象将文件存储至storage中。
    这里只是用于演示storage结合TmpFS使用,如果单纯使用storage服务大可不必这么麻烦,直接调用SaeStorage的write方法即可。

    public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("gbk");
            PrintWriter out = response.getWriter();
            // 使用SaeUserInfo拿到改请求可写的路径
            String realPath = SaeUserInfo.getSaeTmpPath() + "/";
            try {
                // 使用common-upload上传文件至这个路径中
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                if (!isMultipart)
                    return;
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setFileSizeMax(1024 * 1024);
                List<FileItem> items = null;
                items = upload.parseRequest(request);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        File fullFile = new File(item.getName());
                        File uploadFile = new File(realPath, fullFile.getName());
                        item.write(uploadFile);
                        // 上传完毕后 使用SaeStorage往storage里面写
                        SaeStorage ss = new SaeStorage();
                        // 使用upload方法上传到域为image下
                        ss.upload("image", realPath + fullFile.getName(),
                                fullFile.getName());
    
                        out.print("upload file:" + realPath + fullFile.getName()
                                + "</br>");
                    }
                }
                out.print("upload end...");
            } catch (Exception e) {
                out.print("ERROR:" + e.getMessage() + "</br>");
            } finally {
                out.flush();
                out.close();
            }
        }
  • 相关阅读:
    (0.12)elasticsearch分布式集群原理(ES7.9)
    (0.9)elasticsearch分布式集群概念
    mysql分库分表【转】
    (0.11)elasticsearch常用查询,REST API的基本约定,ES增删查改
    mysql全日志自动化脚本
    Java虚拟机--类加载的过程
    Java虚拟机--运行时数据区域
    新题型|结构不良题
    恒等变形的是与非
    分形图与二阶数列
  • 原文地址:https://www.cnblogs.com/x_wukong/p/3724648.html
Copyright © 2011-2022 走看看