在request.getInputStream中为同一文件接收不同的长度

时间:2011-12-19 15:10:08

标签: java javascript file jsp upload

我的网站上有一个文件上传器,因为我不能使用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 I的大小不同,假设request.getInputStream接收到额外的数据。

我只发布了我认为重要的代码,如果我需要发布更多内容,或者如果您需要更多信息,请不要犹豫。

1 个答案:

答案 0 :(得分:0)

简单请求

问题是request.getContentLength()给出整个请求的长度,包含标题和所有。

您必须搜索Content-Length标头值,将其转换为Long并且大小合适。

如果你不能得到它(它可以不可用)只需消耗整个输入流。但是,当然,你不会知道文件大小。

多部分请求

无论如何......因为你的表单是multipart / form-data你应该使用一些库来解析所有不同的部分,找到你需要的部分(文件部分)并阅读它。您可以使用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();
    }
}