Michaelssss
V2EX  ›  Java

[求助] 写了个 servlet,然后发现上传文件的时候永远是 8kb。。。

  •  1
     
  •   Michaelssss · Feb 5, 2017 · 3783 views
    This topic created in 3417 days ago, the information mentioned may be changed or developed.
    我看过前 8kb 和我上传的文件内容是一致的,但是后面所有信息丢失,代码如下:
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println(req.getContentLength());
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(req.getContentLength());
    IOUtils.copy(req.getInputStream(), byteArrayOutputStream);
    byte[] bytes = byteArrayOutputStream.toByteArray();
    Path path = Paths.get(rootPath + "/" + new PathGenerator(bytes).getPath());
    storage.put(byteArrayOutputStream.toByteArray(), path);
    }

    private static void copy(InputStream in, OutputStream op, int length) throws IOException {
    byte[] bytes = new byte[length];
    while (in.available() > 0) {
    int readLength = in.read(bytes);
    op.write(bytes, 0, readLength);
    }
    }
    3 replies    2017-02-05 21:14:10 +08:00
    pagxir
        1
    pagxir  
       Feb 5, 2017 via Android   ❤️ 2
    (in.available() > 0) 这里有问题的,要读到 eof 为止。因为网络是分片传输的,所以某一刻没有数据有效,不代表数据读完整
    Michaelssss
        2
    Michaelssss  
    OP
       Feb 5, 2017
    @pagxir 谢谢还真是。。。
    az999
        3
    az999  
       Feb 5, 2017
    @pagxir 学习了。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5857 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 03:08 · PVG 11:08 · LAX 20:08 · JFK 23:08
    ♥ Do have faith in what you're doing.