代码之家  ›  专栏  ›  技术社区  ›  Jas Ahluwalia

Spark Java中的InputStream和文件上传

  •  0
  • Jas Ahluwalia  · 技术社区  · 7 年前

    getInputStream() 似乎此时正在读取整个文件。这不应该只在我尝试从输入流读取时发生吗?如果我错了,有人能为我提供指导吗?

    post("/encrypt", (req, res) -> {
            try {                
                req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("ProtectCS"));
                Part p = req.raw().getPart("uploaded_file");
                InputStream input = p.getInputStream();
            } catch (Exception e) {
                logger.error(e.getMessage());
                res.status(500);
                return e.getMessage();
            }
            res.status(201);
            return "Success";
    });
    

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mithfindel    7 年前

    考虑到您的用例(可能是由第三方库读取的大文件上传),我会绕过Spark/Jetty的多部分支持,使用例如 Apache Commons FileUpload :

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    
    // Parse the *raw* request
    FileItemIterator iter = upload.getItemIterator(request.raw());
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.getInputStream();
        if (item.isFormField()) {
            System.out.println("Form field " + name + " with value "
                + Streams.asString(stream) + " detected.");
        } else {
            System.out.println("File field " + name + " with file name "
                + item.getName() + " detected.");
            // Process the input stream
            ...
        }
    }
    

    流式API ,所以这可能就是您想要的(以避免缓冲整个 InputStream