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

Add a file size limit to my XMLHttpRequest file upload

我在我的应用程序中使用 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);

您应该在服务器端执行此操作,return 如果文件大小超过 5mb,则会出现异常。您还可以通过 event.file 在客户端验证它,它有一个 "size" 属性,您可以从那里获取 fize 大小。

if((event.file.size / (1024*2)) > 5) {
    console.log('do your logic here');
}

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

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