alejorivera
alejorivera

Reputation: 935

Add a file size limit to my XMLHttpRequest file upload

I'm using Trix (https://github.com/basecamp/trix) as a text-editor in my app and allow for file uploads through there. I want to add a 5mb max file size to my uploads, but am a little lost at how to go about it. How would you implement it?

(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);

Upvotes: 1

Views: 1723

Answers (2)

pmhoudry
pmhoudry

Reputation: 36

You should do it client side AND server side. For the client side, just add one condition like so :

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

Also you can look at this Gist i wrote, showing a full implementation : https://gist.github.com/pmhoudry/a0dc6905872a41a316135d42a5537ddb

Upvotes: 2

Pedro Papadópolis
Pedro Papadópolis

Reputation: 403

You should do it on server side and return an exception if the file size exceeds 5mb. You can also validate it on client-side through event.file, it has an "size" attribute, you can get the fize size from there.

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

Upvotes: 1

Related Questions