簡體   English   中英

為我的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);

您應該在服務器端執行此操作,如果文件大小超過5mb,則返回異常。 您還可以通過event.file在客戶端對其進行驗證,它具有“ size”屬性,您可以從那里獲取裝訂尺寸。

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

您應該在客戶端和服務器端進行操作。 對於客戶端,只需添加一個條件,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM