2014-10-03 58 views
2

我使用Jetty 9的實現HttpServletRequest#getPart(name),它似乎在繼續之前熱切地處理整個請求(或至少Part問題),即使產生的Part公開了一種getInputStream()方法。如何懶惰地使用HttpServletRequest#getPart(name)

getPart是否有立即返回的方法,並且請求流式傳輸到結果PartInputStream

僅供參考,這裏是從我的Servlet執行相關片段:

override def doPost(req: HttpServletRequest, res: HttpServletResponse) { 
    println("ABOUT TO GET PART") // this happens immediately 
    val file = req.getPart("file") 
    println("GOT PART") // it takes a long time to get here if the upload is large 

回答

1

這是邪惡的單調乏味,但是這可以通過使用MultipartStream從來完成:

try { 
    MultipartStream multipartStream = new MultipartStream(input, boundary); 
    boolean nextPart = multipartStream.skipPreamble(); 
    OutputStream output; 
    while(nextPart) { 
    String header = multipartStream.readHeaders(); 
    // process headers 
    // create some output stream 
    multipartStream.readBodyData(output); 
    nextPart = multipartStream.readBoundary(); 
    } 
} catch(MultipartStream.MalformedStreamException e) { 
    // the stream failed to follow required syntax 
} catch(IOException e) { 
    // a read or write error occurred 
} 

這需要使用的InputStream from HttpServletRequest#getInputStream(),以及在HTTP請求的內容類型中編碼的邊界分隔符:

Content-Type: multipart/form-data; boundary=------------------------bd019839518ca918