Javascript 将文件大小限制添加到我的XMLHttpRequest文件上载

Javascript 将文件大小限制添加到我的XMLHttpRequest文件上载,javascript,ajax,xmlhttprequest,Javascript,Ajax,Xmlhttprequest,我在我的应用程序中使用Trix()作为文本编辑器,并允许通过它上传文件。我想在我上传的文件中增加一个5mb的最大文件大小,但我对如何进行有点不知所措。您将如何实施它 (function() { var createStorageKey, host, uploadAttachment; document.addEventListener("trix-attachment-add", function(event) { var attachment; attachment

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

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


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


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

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;
}

您还可以查看我写的这个要点,它展示了一个完整的实现:

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

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;
}
此外,您还可以查看我写的这个要点,它展示了一个完整的实现: