EmilMoe's avatar
Level 10

Upload file from JavaScript

How can I send a file to upload from my JavaScript form? All my text inputs are sent to the server with Vue Resource AJAX requests, but I haven't been able to figure out, how I'm sending data from <input type="file">?

0 likes
5 replies
tykus's avatar

Is your form tag properly formed with enctype="multipart/form-data"?

jekinney's avatar
jekinney
Best Answer
Level 47

If you're uploading with Ajax via JavaScript (vue resourse is a wrapper for JavaScript Ajax) you don't need to use encrypt type in your form element. Matter of fact you don't need a form element tag at all, but should for proper HTML and action and method are also not required.

http://blog.teamtreehouse.com/uploading-files-ajax

Quick search to help you. But you need to use FormData() and set your file to the FormData method in JavaScript.

https://developer.mozilla.org/en-US/docs/Web/API/FormData

2 likes
EmilMoe's avatar
Level 10

I'm not quiet sure how to implement that? This is clearly wrong:

store() {
    var formData = new FormData();
    formData.append('file', this.$els.file[0]);

    this.$http.post('api/v1/notes', {
        title: this.$refs.title.value,
        user:  this.$refs.users.value.id,
        file:  formData.get('file')
    }).then(response => {
    });
}
EmilMoe's avatar
Level 10

I guess this is a step closer, but I'm not referering to the file the right way

store() {
    var self     = this;
    var formData = new FormData();
    formData.append('file',    this.$els.file);
    formData.append('title',   this.$refs.title.value);
    formData.append('user_id', this.$refs.user.value.id);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'api/v1/notes', true);

    xhr.onload = function () {
        if (xhr.status === 200) {
            self.load();
            self.unloadModals();
        }
        else {
            console.error('An error occurred!');
        }
    };

    xhr.send(formData);
}
EmilMoe's avatar
Level 10

I needed to make a slight change to the 4th line

store() {
    var self     = this;
    var formData = new FormData();
    formData.append('file',    this.$els.file.files[0]);
    formData.append('title',   this.$refs.title.value);
    formData.append('user_id', this.$refs.user.value.id);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'api/v1/notes', true);

    xhr.onload = function () {
        if (xhr.status === 200) {
            self.load();
            self.unloadModals();
        }
        else {
            console.error('An error occurred!');
        }
    };

    xhr.send(formData);
}

Thanks !

1 like

Please or to participate in this conversation.