限制JSF中的文件上传大小 [英] Restricting file upload size in JSF

查看:118
本文介绍了限制JSF中的文件上传大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Tomahawk inputFileUpload组件,以允许用户将文件上传到服务器.我已经实现了软"文件大小的限制,方法是检查文件上传后的大小,如果文件太大则显示错误.但是,我还希望有一个更大的硬"​​限制,一旦超过该限制,上传将立即停止.例如,如果硬限制为500MB,并且用户尝试上传2GB的文件,则上传500MB并显示错误后,上传将立即停止.

I am using the Tomahawk inputFileUpload component to allow users to upload files to a server. I have implemented a "soft" file size limit by checking the size of the file after it has been uploaded and displaying an error if it is too large. However I would also like a larger "hard" limit, where uploading immediately stops once it has passed the limit. For example if the hard limit is 500MB and the user attempts to upload a 2GB file, uploading will immediately stop once 500MB has been uploaded and an error is displayed.

我曾希望使用MyFaces ExtensionsFilter并设置uploadMaxFileSize可以解决此问题,但是在抛出SizeLimitExceededException之前,文件已完全上传.

I had hoped that using the MyFaces ExtensionsFilter and setting uploadMaxFileSize would fix the problem, but the file is completely uploaded before the SizeLimitExceededException is thrown.

是否可以这样做?理想情况下,我仍然可以使用战斧",但是任何其他解决方案都可以.

Is it possible to do this? Ideally I'd still be able to use Tomahawk but any other solution would be good.

推荐答案

Web服务器无法中途中止HTTP请求,然后返回HTTP响应.必须完全消耗整个HTTP请求,直到可以返回HTTP响应的最后一位为止.这就是HTTP和TCP/IP的本质.使用服务器端编程语言,您无能为力.

The web server can't abort a HTTP request halfway and then return a HTTP response. The entire HTTP request has to be consumed fully until the last bit before a HTTP response can ever be returned. That's the nature of HTTP and TCP/IP. There's nothing you can do against it with a server side programming language.

请注意,"Tomahawk"文件的上传大小限制已引起注意,只要达到该大小限制,服务器的内存/磁盘空间就不会被整个上传的文件所污染.

Note that the Tomahawk file upload size limit already takes care that the server's memory/disk space won't be polluted with the entire uploaded file whenever the size limit has been hit.

您最好的选择是在上传之前验证JavaScript中的文件长度.浏览器支持 HTML5

Your best bet is to validate the file length in JavaScript before the upload takes place. This is supported in browsers supporting HTML5 File API. The current versions of Firefox, Chrome, Safari, Opera and Android support it. IE9 doesn't support it yet, it'll be in the future IE10.

<t:inputFileUpload ... onchange="checkFileSize(this)" />

带有这样的内容

function checkFileSize(inputFile) {
    var max = 500 * 1024 * 1024; // 500MB

    if (inputFile.files && inputFile.files[0].size > max) {
        alert("File too large."); // Do your thing to handle the error.
        inputFile.value = null; // Clears the field.
    }
}

这篇关于限制JSF中的文件上传大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆