javascript - 为我的 XMLHttpRequest 文件上传添加文件大小限制

标签 javascript ajax xmlhttprequest

我在我的应用程序中使用 Trix ( https://github.com/basecamp/trix ) 作为文本编辑器,并允许通过那里上传文件。我想在上传时添加最大 5mb 的文件大小,但我不知道如何操作。您将如何实现它?

(function() {
  var createStorageKey, host, uploadAttachment;

  document.addEventListener("trix-attachment-add", function(event) {
    var attachment;
    attachment = event.attachment;
    if (attachment.file) {
      return uploadAttachment(attachment);
    }
  });

  host = "https://my.cloudfront.net/";

  uploadAttachment = function(attachment) {
    var file, form, key, xhr;
    file = attachment.file;
    key = createStorageKey(file);
    form = new FormData;
    form.append("key", key);
    form.append("Content-Type", file.type);
    form.append("file", file);
    xhr = new XMLHttpRequest;
    xhr.open("POST", host, true);
    xhr.upload.onprogress = function(event) {
      var progress;
      progress = event.loaded / event.total * 100;
      return attachment.setUploadProgress(progress);
    };
    xhr.onload = function() {
      var href, url;
      if (xhr.status === 204) {
        url = href = host + key;
        return attachment.setAttributes({
          url: url,
          href: href
        });
      }
    };
    return xhr.send(form);
  };

  createStorageKey = function(file) {
    var date, day, time;
    date = new Date();
    day = date.toISOString().slice(0, 10);
    time = date.getTime();
    return "tmp/" + day + "/" + time + "-" + file.name;
  };

}).call(this);

最佳答案

您应该在客户端和服务器端执行此操作。对于客户端,只需添加一个条件,如下所示:

file = attachment.file;
if (file.size == 0) {
    attachment.remove();
    alert("The file you submitted looks empty.");
    return;
} else if (file.size / (1024*2)) > 5) {
    attachment.remove();
    alert("Your file seems too big for uploading.");
    return;
}

你也可以看看我写的这个要点,显示了完整的实现:https://gist.github.com/pmhoudry/a0dc6905872a41a316135d42a5537ddb

关于javascript - 为我的 XMLHttpRequest 文件上传添加文件大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486142/

相关文章:

css - 如何确保在 AJAX 内容之前首先加载动态 CSS?

javascript - 如何在 Safari 4 中调试 XHR POST 请求?

javascript - XMLHttpRequest 已弃用。用什么代替?

javascript - 修改XMLHttpRequest数据

javascript - require 未定义,使用 polyfill 来修复Promise 未在 IE 11 上定义

javascript - ajax调用后注入(inject)JavaScript

javascript - CSV 数据和 JS/HTML

php - 如何使用 ajax post 和 url 的放大弹出窗口?

javascript - 使用 jQuery 添加空图像标签

javascript - 突出显示 ASP.NET Core 的 Kendo UI 网格中的空单元格