[英]HTTPServlet Request.getInputStream() always receiving blank line
[英]Receiving varying lengths in request.getInputStream for the same file
我的網站上有一個文件上傳器,因為我無法使用php,因此我正在使用jsp頁面。 我的主頁使用隱藏的iframe將數據發布到第二個處理上傳的jsp頁面。 但是,上傳的圖像始終會損壞,更具體地說,其大小會比原始文件大。 任何提示或技巧將不勝感激。 主頁代碼:
<form id="uploadForm">
<input type="file" name="datafile" /></br>
<input type="button" value="upload" onClick="fileUpload(document.getElementById('uploadForm'),'single_upload_page.jsp','upload'); return false;" >
</form>
fileUpload的代碼涉及以下形式:
form.setAttribute("target","upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
// Submit the form...
form.submit();
處理上傳的代碼:
DataInputStream in = new DataInputStream(request.getInputStream());
int dataLength = request.getContentLength();
由於dataLength大小的變化,我假設request.getInputStream接收到額外的數據。
我只發布了我認為重要的代碼,如果我需要發布更多代碼,或者如果您需要更多信息,請隨時詢問。
簡單的要求
問題是request.getContentLength()給出了整個請求的長度,包括標頭和全部。
您必須搜索Content-Length標頭值,將其轉換為Long,這是正確的大小。
如果您無法獲得它(它可能不可用),則只需消耗整個輸入流即可。 但是,當然,您對文件的大小一無所知。
多部分要求
無論如何...由於您的表單是多部分/表單數據,因此您應該使用一些庫來解析所有不同的部分,找到所需的部分(文件部分)並閱讀。 您可以使用commons-fileupload 。
現實生活中的樣本
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException
{
// (....)
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
FileItemIterator it = sfu.getItemIterator(request);
// TAKE THE FIRST PART FROM REQUEST (HERE COMES THE FILE)
if (it.hasNext())
{
FileItemStream fis = it.next();
// grab data from fis (content type, name)
...fis.getContentType()...
...fis.getName()...
// GET CONTENT LENGTH SEARCH FOR THE LENGTH HEADER
...getContentLength(fis.getHeaders(), request)...
// here I use an own method to process data
// but FileItemStream has an openStream method
FileItem item = processUpload(factory, fis, uploadInfo);
(....)
}
private long getContentLength(FileItemHeaders pHeaders, HttpServletRequest request)
{
try
{
return Long.parseLong(pHeaders.getHeader("Content-length"));
}
catch (Exception e)
{
// if I can't grab the value return an approximate (in my case I don't care)
return request.getContentLength();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.