如何在 JavaScript 中确定文件大小?

发布于 2024-07-27 03:54:05 字数 696 浏览 7 评论 0原文

我帮助管理一个在线论坛,在这个论坛上我们限制签名的大小。 目前,我们通过我编写的一个简单的 Greasemonkey 脚本对此进行了测试; 我们用

包装所有签名,脚本查找它们,然后测量 div 的高度和宽度。

脚本现在所做的就是确保签名位于特定的高度/宽度。 我想开始自动测量签名内图像的文件大小,以便脚本可以自动标记在签名中包含巨大图像的用户。 但是,我似乎找不到一种方法来测量页面上加载的图像的大小。 我搜索并找到了 IE 特有的属性(element.fileSize),但我显然不能在我的 Greasemonkey 脚本中使用它。

有没有办法通过 JavaScript 找出 Firefox 中图像的文件大小?

编辑:人们误解了这个问题。 论坛本身不托管图像; 我们托管人们输入作为签名的 BBCode。 例如,人们输入:

This is my signature, check out my [url=http://google.com]awesome website[/url]!
This image is cool!  [img]http://image.gif[/img]

我希望能够通过 Greasemonkey 检查这些图像。 我可以编写一个批处理脚本来扫描所有这些,但我只是想知道是否有一种方法可以增强我当前的脚本。

I help moderate a forum online, and on this forum we restrict the size of signatures. At the moment we test this via a simple Greasemonkey script I wrote; we wrap all signatures with a <div>, the script looks for them, and then measures the div's height and width.

All the script does right now is make sure the signature resides in a particular height/width. I would like to start measuring the file size of the images inside of a signature automatically so that the script can automatically flag users who are including huge images in their signature. However, I can't seem to find a way to measure the size of images loaded on the page. I've searched and found a property special to IE (element.fileSize) but I obviously can't use that in my Greasemonkey script.

Is there a way to find out the file size of an image in Firefox via JavaScript?

Edit: People are misinterpreting the problem. The forums themselves do not host images; we host the BBCode that people enter as their signature. So, for example, people enter this:

This is my signature, check out my [url=http://google.com]awesome website[/url]!
This image is cool!  [img]http://image.gif[/img]

I want to be able to check on these images via Greasemonkey. I could write a batch script to scan all of these instead, but I'm just wondering if there's a way to augment my current script.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

烟柳画桥 2024-08-03 03:54:05

如您所知,IE 支持图像的 fileSize 属性。 在其他浏览器中没有这样的运气......但是,您应该能够修改此脚本:

http ://natbat.net/2008/Aug/27/addSizes/

它使用 JSON 读取文件的 HTTP 标头并显示其实际文件大小。 这应该可以帮助您防止人们上传大型动画 GIF。

至于获取尺寸:

var img = new Image();
theImage.src = "someimage.jpg";
actualwidth = theImage.width;
actualheight = theImage.height;

这当然是一种纯粹的客户端方法,最好在服务器端处理。

As you know IE supports the fileSize property of an image. No such luck in other browsers ... however, you should be able to modify this script:

http://natbat.net/2008/Aug/27/addSizes/

It uses JSON to read HTTP headers of files and display their actual file size. That should help you prevent people uploading large animated GIFs.

As for getting the dimensions:

var img = new Image();
theImage.src = "someimage.jpg";
actualwidth = theImage.width;
actualheight = theImage.height;

This of course is a pure client-side approach to something best handled server-side.

三生池水覆流年 2024-08-03 03:54:05

实际上,使用 HTML5,这现在是可能的,
请在此处阅读更多信息。

Actually, with HTML5, this is now possible,
read more information here.

枉心 2024-08-03 03:54:05

简短的回答,你不能

另外,检查 jGuru 如何检查文件大小JavaScript 在带有文件输入类型的表单中?

你会发现一些要点

答案很简单,你不能。

原因:浏览器安全不允许脚本
(Javascript/VBScript) 甚至小程序和 ActiveX 控件来读取
来自本地硬盘的文件。 您只能读取文件,如果您的代码
由某个证书颁发机构 (CA) 签名。 现在输入类型
“FILE”也没有读取文件的权限。 我们做不到
任何关于这个的事情,因为 HTML 就是这么说的。 所以既然不能
读取文件,它无法找到输入的文件的大小
标签已关联。 由于无法找到文件大小,因此没有
JavaScript/VBScript 公开的用于返回文件大小的函数。 但
如果您需要查找文件大小,请说是为了限制大小
上传到您的网络服务器的文件。 然后你可以这样做
用户提交后,在服务器端计算文件内容
它到服务器。 这就是许多免费电子邮件提供商所喜欢的
www.hotmail.com 可以。

Short answer, you cannot

Also, Check on jGuru How can you check the file size from JavaScript in a form with an input type of file?

You will find some important points

Well the answer is very simple, you cannot.

Reason: The browser security does not allow the scripts
(Javascript/VBScript) or even applets and ActiveX Controls to read
files from the local hard disk. You can only read files if your code
is signed by some Certificate Authority (CA). Now the input type
"FILE" also does not have the permission to read files. We cannot do
anything about that since thats what HTML says. So since it cannot
read files, it cannot find the size of the file with which the input
tag is associated. Since it cannot find the file size, there is no
function exposed by JavaScript/VBScript to return the file size. But
if you need to find the file size, say in order to restrict the size
of the file uploaded to your web-server. Then you can do so by
counting the file contents on the server-side, once the user submits
it to the server. Thats what many of the free e-mail providers like
www.hotmail.com do.

执笔绘流年 2024-08-03 03:54:05

服务器端验证始终是更好的选择,但就您而言,我可以理解为什么您想要执行此客户端操作。

另外,似乎其他人可能误读了这个问题,并且丹尼尔想要测试的图像已经上传,在这种情况下,有一个相当简单的方法可以这样做(前提是图像与脚本位于同一域中) 。

var getFileSize = function(address, responseHandler) {
  var req = new XMLHttpRequest();  

  req.open('head', address, true);  
  req.onreadystatechange = responseHandler;
  req.send(null);  
}

var responseHandler = function(resp) {
  if ( this.readyState == 1 ) {
    this.abort();
  }
  console.log(this.getResponseHeader("Content-length"));
};

getFileSize("http://stackoverflow.com/content/img/so/logo.png", responseHandler);

繁荣。 此示例适用于 FF3 或 FF2。由于您使用 Greasemonkey 来执行此操作,因此浏览器兼容性似乎不是问题。

我不确定 Greasemonkey 是否共享相同的 XML RPC 域限制,但如果您需要的图像文件位于与脚本不同的域中,那么您可能需要考虑使用一些 iframe 魔法。

Server side validation is always a better bet, but in your case, I can see why you would want to do this client side.

Also, it seems that others may have misread the question, and that the images that Daniel want to test are already uploaded, in which case there is a fairly simple method of doing so (provided the images are on the same domain as the script).

var getFileSize = function(address, responseHandler) {
  var req = new XMLHttpRequest();  

  req.open('head', address, true);  
  req.onreadystatechange = responseHandler;
  req.send(null);  
}

var responseHandler = function(resp) {
  if ( this.readyState == 1 ) {
    this.abort();
  }
  console.log(this.getResponseHeader("Content-length"));
};

getFileSize("http://stackoverflow.com/content/img/so/logo.png", responseHandler);

Boom. This example works in FF3 and probably 2. Since you're using Greasemonkey to do this, browser compatibility doesn't seem like an issue.

I'm not certain if Greasemonkey shares the same XML RPC domain restrictions, but if the images files that you need are on a different domain than the script, then you might need to look into using some iframe magic.

忆悲凉 2024-08-03 03:54:05

客户端验证不足以实现您的目标。 一个简单的 post 请求将允许用户上传他们想要的任何图像,无论您为他们提供什么 html 或 javascript。

Client side validation is insufficient to accomplish your goal. A simple post request will allow the user to upload any image they want no matter what html or javascript you serve them.

╄→承喏 2024-08-03 03:54:05

您可以在上传文件的 HTML 中设置最大文件大小。

<input type="hidden" name="MAX_FILE_SIZE" value="10000000">

(最大文件大小以字节为单位)。

然而,这是某些浏览器的“未记录/不受支持”的项目。 上传后,您最好在服务器上实际检查文件大小。

您还可以使用 Flash 或 Java 小程序来处理上传并检查文件大小。 请参阅 http://www.masrizal。 com/product/custom%20tag/cf_flashmultiupload/docs%20&%20examples/example.cfmhttp://www.saschawenning.de/labor/flash8/fileUpload/ 例如。

You could set a maximum file size in your HTML where they upload files.

<input type="hidden" name="MAX_FILE_SIZE" value="10000000">

(max_file_size in bytes).

However, this is an "undocumented/unsupported" item of some browsers. You are best to actually check the filesize on the server once it's been uploaded.

You could also use a Flash or Java applet to handle the upload and check the filesize there. See http://www.masrizal.com/product/custom%20tag/cf_flashmultiupload/docs%20&%20examples/example.cfm and http://www.saschawenning.de/labor/flash8/fileUpload/ for examples.

江心雾 2024-08-03 03:54:05

DOM 属性 img.fileSize 将返回引用的 的实际文件大小。 可以使用 JQuery 或 DOM“图像”集合来访问 img 对象。 然而,这是一个仅限 IE 的扩展。

另一种方法是省略 中的高度和宽度属性。 标记,以便下载完整图像,然后使用 img.height 和 img.width 确定下载图像的大小。 可以将此代码放入用户的个人资料编辑器页面中,作为让某人以 HTML 形式输入签名和向他们显示签名预览之间的中间步骤。 我不得不承认,虽然笨拙,但还是有可能的。

The DOM attribute img.fileSize will return the actual file size of the referenced <img>. Access to the img object can be obtained using JQuery or the DOM 'images' collection. However, this is an IE only extension.

Another approach is to omit the height and width attributes in the <img> tag, so that the full image is downloaded, then use img.height and img.width to determine the size of the downloaded image. This code could be put into the user's profile editor page as an intermediate step between having someone enter their signature as HTML, then showing them a preview of their signature. Clunky, I have to admit, but possible.

み格子的夏天 2024-08-03 03:54:05

如果您担心巨大的图像,请像 Richy C. 提到的那样设置最大上传大小,但也要在服务器上调整上传图像的大小并使用调整大小的版本。

Facebook 对大多数上传的图像执行此操作,以便提供合理大小的图像。 甚至在某些(大多数?)情况下将它们转换为 png 格式,这会让创意团队因为“质量下降”而发疯。

If you are worried about huge images, set a max upload size as Richy C. mentioned, but also resize the uploaded image on the server and use the resized version.

Facebook does this for most of the uploaded images so that reasonably size images are served. Even converting them to png format in some (most?) cases, which drive the creative group nuts because of "lost quality".

牵你的手,一向走下去 2024-08-03 03:54:05

您应该能够做的是图像 url 的 AJAX HEAD 请求,它只获取文件的标头而不是内容,因此速度要快得多。 您将返回的标头之一是 Content-Length,它将告诉您图像的大小(以字节为单位)。

更多详细信息请参见此处

What you should be able to do is an AJAX HEAD request of the image url, which just gets the header of the file rather than the contents, so is much faster. One of the headers you will get back is Content-Length, and that will tell you the size of the image in bytes.

More details here.

清醇 2024-08-03 03:54:05

您可以执行该文件 HTML5 JS File API

您可以在我的 Web IDE 中测试运行以下代码(但请使用 google chrome 或 FF):
http://codesocialist.com/#/?s=bN

以下代码检索文件类型和文件大小给你:)

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {

    // Great success! All the File APIs are supported.
    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
          output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes </strong></li>');
        }

        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    }

    // Bind Event Listener
    document.getElementById('files').addEventListener('change', handleFileSelect, false);

} else {
    alert('The File APIs are not fully supported in this browser.');
}

You can do that file HTML5 JS File API

You can test run the below codes in my web IDE (but please use google chrome or FF):
http://codesocialist.com/#/?s=bN

The below codes retrieve the filetype and filesize for you :)

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {

    // Great success! All the File APIs are supported.
    function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // files is a FileList of File objects. List some properties.
        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
          output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes </strong></li>');
        }

        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    }

    // Bind Event Listener
    document.getElementById('files').addEventListener('change', handleFileSelect, false);

} else {
    alert('The File APIs are not fully supported in this browser.');
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文