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

时间:2016-02-18 15:51:32

标签: 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);

2 个答案:

答案 0 :(得分:1)

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

https://www.dropbox.com/s/gltf6smnyo7jua0/Screenshot%202016-03-30%2021.09.02.png?dl=1

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

答案 1 :(得分:1)

你应该做客户端和服务器端。对于客户端,只需添加一个条件:

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

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