Sie sind auf Seite 1von 30

03/01/2019 Uploading Files With VueJS and Axios - Server Side Up

(/)
Home (/)

Courses (/search/?
type=courses)

Tutorials (/search/?
type=tutorials)

VUE

Uploading Files With VueJS and Axios

VueJS and Axios GitHub – axios/axios: Promise based HTTP client for
the browser and node.js (https://github.com/axios/axios) work
Dan Pastori
beautifully together for makingDecember
HTTP requests. However, uploading files
13th, 2017
with VueJS and Axios can be a little bit challenging since it requires
uploading files through an AJAX type system. I’ll be honest, I hate doing
file uploads, but they are a necessity for the majority of applications. This
tutorial should be a quick start guide on the process and a few tips I’ve
learned when handling file uploads to make your life a little easier.

Prerequisites
Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
1/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up
In this tutorial
uploading- API I’m going to be using Axios v0.16.2 and VueJS v2.1.0 for
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files- doing the file uploads. On the back end you can use the framework that
App
vuejs-
you want, or language that you want. I’ll talk about using PHP/Laravel to
Development?
axios/) We're
processwriting
files and more or less pseudo-code the backend process. The
a book
biggestontake
API aways will be how to do the uploading of the file with VueJS
Driven
and Axios.
App
Development.
Be the
first to
I’m alsoknow
going to assume you are using a modern browser that supports
once it
the FormData
is
ready!
object: FormData – Web APIs | MDN
(https://developer.mozilla.org/en-US/docs/Web/API/FormData). This
is what makes the process a whole heck of a lot easier.

Uploading a Single File


So first, we will start with a single file to get things going. I just built a
simple component that contains a file input:

<template>
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>File
<input type="file" id="file" ref="file" v-on:change="handleFileUplo
</label>
<button v-on:click="submitFile()">Submit</button>
</div>
</div>
</template>

If you take a look at the input[type="file"] I added a few


attributes. The first is a ref attribute that gives this input a name. We
can now access this input from within VueJS which we will in a second.

The next is the v-on:change="handleFileUpload()" attribute.


When the user uploads a file, this gets called and we can handle the file.
We will be implementing this method in the next step.

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
2/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
files-
The lastDriven
element in the simple form is a button that calls a method
App
Development?when
vuejs-submitFile() clicked. This is where we will submit our file to
axios/) We're
the server and we will be implementing this method as well.
writing
a book
on API
Handle User File Upload
Driven
App
Development.
The first
Be thing
the we want to do is add the handleFileUpload() method
first to
to our methods
know object which will give us a starting point for
once it
implementation:
is
ready!
<script>
export default {
methods: {
handleFileUpload(){

}
}
}
</script>

What we will do in this method is set a local variable to the value of the
file uploaded. Now since we are using a modern browser, this will be a
FileList object: FileList – Web APIs | MDN
(https://developer.mozilla.org/en-US/docs/Web/API/FileList) which
contains File objects: File – Web APIs | MDN
(https://developer.mozilla.org/en-US/docs/Web/API/File). The
FileList is not directly editable by the user for security reasons.
However, we can allow users to select and de-select files as needed, which
we will go through later in the tutorial.

Since we are setting a local piece of data, let’s add that right now to our
Vue component. In our data() method add:

data(){
return {
file: ''
}
},
Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
3/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up
Now weAPIhave something
uploading- to set in our handleFileUpload() method!
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files- Let’s go back and add the following code to the handleFileUpload()
App
vuejs-
method: Development?
axios/) We're
writing
a book
methods: {
on API
handleFileUpload(){
Driven
this.file
App = this.$refs.file.files[0];
} Development.
} Be the
first to
know
What this
oncedoes
it is when the file has been changed, we set the local file
is
variableready!
to the first File object in the FileList on the
input[type="file"] . The this.$refs.file refers to the ref
attribute on the the input[type="file"] . This makes it easily
accessible within our component.

Submit To Server Through Axios


Now it’s time to submit our file through the server through Axios! On our
button, we have a submitFile() method we need to implement, so
let’s add this to our methods:

submitFile(){

},

Now this is where we implement our axios request.

The first thing we need to do is implement a FormData object like this:

let formData = new FormData();

Next, what we will do is append the file to the formData . This is done
through the append() method on the object: FormData.append() –
Web APIs | MDN (https://developer.mozilla.org/en-
US/docs/Web/API/FormData/append). What we are doing is essentially
building a key-value pair to submit to the server like a standard POST
request:
Want to Next
learn
formData.append('file',
Get Updates
this.file); File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
4/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up
We justAPI
uploading- append the file variable that we have our data stored in. Now I’m
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files- not going to go into validations, but before we go any further, if you were
App
vuejs-
to put this in production and the file needed to be added, I’d add a
Development?
axios/) We're
validation here to make sure the file variable contains an actual file.
writing
a book
on API
Driven
Now weApp can begin to make our axios request! We will be doing this
Development.
throughBethe
the post() method. If you look at their API (GitHub –
first to
axios/axios:
know Promise based HTTP client for the browser and node.js
once it
(https://github.com/axios/axios#axiosposturl-data-config)),
is
ready!
you see the
post() method contains 3 parameters. The third parameter is a config
for the request which is awesome because we can add other headers to it.

Our completed request should look like:

axios.post( '/single-file',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
});

The first parameter is the URL we will be POSTing to. For this example, I
have a URL set up on my server which is /single-file . The next
parameter is a key-value store of the data we are passing. This is our
FormData() which we built to have our file. The third parameter is
probably the key to making this all work. This is adding the
multipart/form-data header we need to send the file to the server.

If you are used to file uploading, this is usually an attribute on the form
you are submitting like <form enctype="multipart/form-data">
</form> . Without
Want to this header, the POST request will ignore the file. Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
5/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
files-
Now with the rest of our request, we process a callback method on a
Driven
App
vuejs-successful request
Development? which can be used to display a notification and we
axios/) We're
processwriting
a callback on failure which can be used to alert the user of an
a book
unsuccessful
on API upload.
Driven
App
On the Development.
server side, you can access the file through the key of
Be the
file which
first to
is the first
know
parameter of the formData.append('file',
once it
this.file);
is method.
ready!

In PHP it’d be: $_FILES['file'] and in Laravel, you can use the
Request facade and access it through Request::file('files')
and do whatever server side processing you need.

Our SingleFile.vue component used for testing looks like this:

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
6/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
<template> u=a27137fc57d223f1cc7b986db&id=1276f15943)
files- <div Driven
class="container">
Appclass="large-12 medium-12 small-12 cell">
<div
vuejs- Development?
<label>File
axios/) We're
<input type="file" id="file" ref="file" v-on:change="handleFileUplo
writing
</label>
a book
<button
on API v-on:click="submitFile()">Submit</button>
</div>
Driven
App
</div>
Development.
</template>
Be the
first to
<script>
know
export
oncedefault
it {
/* is
ready!
Defines the data used by the component
*/
data(){
return {
file: ''
}
},

methods: {
/*
Submits the file to the server
*/
submitFile(){
/*
Initialize the form data
*/
let formData = new FormData();

/*
Add the form data we need to submit
*/
formData.append('file', this.file);

/*
Make the request to the POST /single-file URL
*/
axios.post( '/single-file',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
}); Next
Want to
}, Get Updates
learn File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
7/30
03/01/2019 about
(https://serversideup.net/courses/guide-
/* Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
Handles a change on the file upload
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
*/
files-
handleFileUpload(){
App
vuejs- this.file = this.$refs.file.files[0];
Development?
axios/) }We're
} writing
} a book
on API
</script>
Driven
App
Development.
The next
Be section,
the
first to
we will handle multiple files. This isn’t anything super
different,
know
but I’ll point out the changes!
once it
is
ready!

Uploading Multiple Files


Handling multiple files is very similar to a single file. What we will do is
begin with a template that looks like this in our Vue component:

<template>
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>Files
<input type="file" id="files" ref="files" multiple v-on:change="han
</label>
<button v-on:click="submitFiles()">Submit</button>
</div>
</div>
</template>

Besides the ref attribute name change and the id changing to files ,
the most important attribute is we added multiple to our
input[type="file”] . This allows the user to cmd (ctrl) + click to
select multiple files at once. A super slick way to upload files. In the next
section we will be allowing the user to remove files and select more files if
they made a mistake but for now, it’s super slick.

Multiple File handleFileUploads() method


This is very similar to an individual file, except we will be adding all of the
files to our array if the user selects more than one. First, let’s add our data
store to our Vue component and give it variable named files :
Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
8/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading-/* API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
Defines the data used by the component
files-
*/ App
vuejs-
data(){Development?
axios/) returnWe're
{
writing
files: ''
a book
} on API
}, Driven
App
Development.
Now weBehave
the a local variable to store our files to. We can now do our
first to
handleFileUploads()
know method:
once it
is
/* ready!
Handles a change on the file upload
*/
handleFilesUpload(){
this.files = this.$refs.files.files;
}

What this does is grab all of the files in the FilesList from our files
upload and stores it locally.

Implement submitFiles() method


We are ready to submit all of our files to the server now! First, let’s add
our submitFiles() method to the methods array:

/*
Submits all of the files to the server
*/
submitFiles(){

},

Like in the last method, we will initialize the FormData() object first:

/*
Initialize the form data
*/
let formData = new FormData();

Now, what we will do is loop over all of the files selected and add them to
the files array we are going to submit to the server. The files array
will be a key in the formData() object we will be sending to the server:
Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
9/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
/* u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
Iteate over any file sent over appending the files
files-
Appform data.
to the
vuejs- Development?
*/
axios/) for( var
We're
i = 0; i < this.files.length; i++ ){
writing
let file = this.files[i];
a book
on API
formData.append('files['
Driven + i + ']', file);
} App
Development.
Be the
We arefirst
now to ready to send our files to the server through Axios:
know
once it
/* is
Make ready!
the request to the POST /multiple-files URL
*/
axios.post( '/multiple-files',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
});

There we go! Now we are allowing users to upload multiple files using
Axios and VueJS through an AJAX call.

On the server side, you can access the files through the key of files
which is the first parameter of the formData.append('files[' + i
+ ']', file); method.

In PHP it’d be: $_FILES['files'] and in Laravel, you can use the
Request facade and access it through Request::file('files')
and do whatever server side processing you need. You can loop through
all of the files now to allow for multiple uploads.

Our MultipleFiles.vue component should look like:


Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
10/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
<template> u=a27137fc57d223f1cc7b986db&id=1276f15943)
files- <div Driven
class="container">
Appclass="large-12 medium-12 small-12 cell">
<div
vuejs- Development?
<label>Files
axios/) We're
<input type="file" id="files" ref="files" multiple v-on:change="han
writing
</label>
a book
<button
on API v-on:click="submitFiles()">Submit</button>
</div>
Driven
App
</div>
Development.
</template>
Be the
first to
<script>
know
export
oncedefault
it {
/* is
ready!
Defines the data used by the component
*/
data(){
return {
files: ''
}
},

methods: {
/*
Submits all of the files to the server
*/
submitFiles(){
/*
Initialize the form data
*/
let formData = new FormData();

/*
Iteate over any file sent over appending the files
to the form data.
*/
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];

formData.append('files[' + i + ']', file);


}

/*
Make the request to the POST /multiple-files URL
*/
axios.post( '/multiple-files',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){ Next
Want to
console.log('SUCCESS!!');
Get Updates
learn File Upload Progress Indicator with Axios and
})
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
11/30
03/01/2019 about
(https://serversideup.net/courses/guide-
.catch(function(){ Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API console.log('FAILURE!!');


u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
});
files-
},
App
vuejs- Development?
axios/) /*
We're
writing
Handles a change on the file upload
a
*/ book
on API
handleFilesUpload(){
Driven
App this.files = this.$refs.files.files;
}Development.
} Be the
} first to
know
</script>
once it
is
ready!
The next step we will allow users to edit the files they have selected so
they don’t accidentally upload a file they don’t want.

Allowing Users to Edit Selected Files Before


Uploading
When uploading multiple files, it’s very common that you accidentally
select a file you do NOT want to upload. This sounds simple enough to
resolve until you find out you can’t directly edit the FileList object for
security reasons. However, you can transform it and edit the new list as
an array and allow users to change the files they want uploaded.

First, let’s reuse the template from the multiple files component:

<template>
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>Files
<input type="file" id="files" ref="files" multiple v-on:change="han
</label>
<button v-on:click="submitFiles()">Submit</button>
</div>
</div>
</template>

Hide File Input


The first thing we will do is hide the actual file input. This is because we
will be Want
making
to a simple design interface to allow users to select the files Next
Get Updates File Upload Progress Indicator with Axios and
they want. learn
I just added a style tag that moves the input off of the screen.
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
12/30
about
(https://serversideup.net/courses/guide-
03/01/2019 Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
- Server Side Up
because manage.com/subscribe?
This is API it’s a security issue to trigger a click on the hidden file
uploading- u=a27137fc57d223f1cc7b986db&id=1276f15943)
files- input.
Driven
App
vuejs- Development?
axios/) <style>We're
input[type="file"]{
writing
a book
position: absolute;
on API
top: -500px;
Driven
}
App
</style>
Development.
Be the
Next, I first
added
know
to
a button that triggers a click on the input:
once it
is
<div class="large-12 medium-12 small-12 cell">
ready!
<button v-on:click="addFiles()">Add Files</button>
</div>

So when this is clicked, we trigger a click on the file element. We need to


implement the addFiles() method in our Vue component like this:

addFiles(){
this.$refs.files.click();
}

This will fire a click on the files input and the user will be prompted with
a file selection box where they can select the files we want.

Implement handleFilesUpload()
This is where things get a little bit different. Like the first two examples,
we will add a local variable to add files to:

data(){
return {
files: []
}
},

We want this as an array so we can push files onto it.

Now, when the user selects some files to upload, we will push them on
our local files variable:

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
13/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
let uploadedFiles = this.$refs.files.files;
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files-
/* App
vuejs-
Adds Development?
the uploaded file to the files array
axios/) */ We're
writing
for( var i = 0; i < uploadedFiles.length; i++ ){
a book
this.files.push(
on API uploadedFiles[i] );
} Driven
App
Development.
We do this
Be thethrough a loop instead of pushing the entire chunk onto the
first to
filesknowarray because otherwise we’d have groups based on what was
once it
selected.
is You can add validations here as well so the user doesn’t upload
ready!
the same file multiple times if you want as well.

Display Currently Uploaded Files


In this use case, we want users to remove files they updated by accident,
so we need to display the currently uploaded files.

To do that, we will head back into our template and add the following
code:

<div class="large-12 medium-12 small-12 cell">


<div v-for="(file, key) in files" class="file-listing">{{ file.name }} <s
</div>
<br>

What this does is iterate over all of the files we’ve currently added and
displays them to the user. A couple things to note.

First, the v-for="(file, key) in files" . What this does is


iterate over the files that we’ve uploaded and grabs the key which is the
index of the file in the files array and the file itself. We then display the
name of the file with: {{ file.name }} which is part of the individual
file object. There’s more information in the object which is documented
here: File – Web APIs | MDN (https://developer.mozilla.org/en-
US/docs/Web/API/File)
Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
14/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
files-
Next, we add a removeFile(key) method which will remove the file
Driven
App
vuejs-from the file array. When the file is removed, the reactive nature of VueJS
Development?
axios/) We're
will update
writing
our listing.
a book
on API
Implement removeFile() Method
Driven
App
Development.
This method
Be the will remove the file from our uploaded files array. First, let’s
first to
add theknow
method to our methods array:
once it
is
removeFile(
ready! key ){

The method accepts the key in the files array of the file we are removing.
The full implementation of this method will be:

removeFile( key ){
this.files.splice( key, 1 );
}

What this does is splice the files array at the index of the file we are
removing and remove 1 entry from the array. When we do this, our list
will re-render through VueJS keeping everything in sync. Since we are
using a local files array, we can modify this at will. The next and final
thing we have to do is submit our files to the server that the user has
selected!

Submit Files To Server


From here, we’ve allowed the user to modify the files they have selected,
we just have to allow them to submit to the server for processing.

First, let’s add the submitFiles() method to our methods object:

submitFiles(){

Like theWant
restto of the examples, let’s first create our FormData() object: Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
15/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading-/* API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven the form data
Initialize
files-
*/ App
vuejs- Development?
let formData = new FormData();
axios/) We're
writing
Now, let’s add all of the chosen files to the form data:
a book
on API
Driven
/* App
Development.
Iterate over any file sent over appending the files
Be the
to the form data.
first to
*/
know
for( var
onceiit = 0; i < this.files.length; i++ ){
let file
is = this.files[i];
ready!
formData.append('files[' + i + ']', file);
}

This iterates over the files that the user has selected and prepares to
submit them to the server.

Now, we can run the axios.post() method to submit the files to our
endpoint:

axios.post( '/select-files',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
});

This sends all of our form data to the server with the files that the user
has uploaded! If you were to run this as an example, you can see that
after you remove a file, it’s no longer sent to the server.

Like before, on the server side, you can access the files through the key of
files which is the first parameter of the
formData.append('files['
Want to + i + ']', file); method. Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
16/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
files-
When using
Driven Laravel and the Request facade, you can access the
App
vuejs-selected files the user
Development? has uploaded with the following method:
axios/) We're
Request::file('files')
writing . In straight up PHP it’d be
a book
$_FILES['files']
on API . You can now do any processing you want!
Driven
App
Our Development.
SelectFiles.vue
Be the
component should look like:
first to
know
once it
is
ready!

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
17/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading-<style>API u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
input[type="file"]{
files-
App
position: absolute;
vuejs- Development?
top: -500px;
axios/) } We're
writing
a book
div.file-listing{
on API
width:
Driven 200px;
} App
Development.
Be the
span.remove-file{
first to
color:
know red;
cursor:
once it pointer;
float:
is right;
} ready!
</style>

<template>
<div class="container">
<div class="large-12 medium-12 small-12 cell">
<label>Files
<input type="file" id="files" ref="files" multiple v-on:change="han
</label>
</div>
<div class="large-12 medium-12 small-12 cell">
<div v-for="(file, key) in files" class="file-listing">{{ file.name }
</div>
<br>
<div class="large-12 medium-12 small-12 cell">
<button v-on:click="addFiles()">Add Files</button>
</div>
<br>
<div class="large-12 medium-12 small-12 cell">
<button v-on:click="submitFiles()">Submit</button>
</div>
</div>
</template>

<script>
export default {
/*
Defines the data used by the component
*/
data(){
return {
files: []
}
},

/*
Defines the method used by the component
*/
methods: { Next
Want to
/* Get Updates
learn File Upload Progress Indicator with Axios and
Adds a file
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
18/30
03/01/2019 about
(https://serversideup.net/courses/guide-
*/ Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
addFiles(){
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
this.$refs.files.click();
files-
},
App
vuejs- Development?
axios/) /*
We're
writing
Submits files to the server
a
*/book
on API
submitFiles(){
Driven
App/*
Initialize the form data
Development.
Be*/ the
firstlet
to formData = new FormData();
know
once it
is /*
ready!Iteate over any file sent over appending the files
to the form data.
*/
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];

formData.append('files[' + i + ']', file);


}

/*
Make the request to the POST /select-files URL
*/
axios.post( '/select-files',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
});
},

/*
Handles the uploading of files
*/
handleFilesUpload(){
let uploadedFiles = this.$refs.files.files;

/*
Adds the uploaded file to the files array
*/
for( var i = 0; i < uploadedFiles.length; i++ ){
this.files.push( uploadedFiles[i] );
}
Want to Next
},
learn Get Updates File Upload Progress Indicator with Axios and
more
/* (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
19/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading
the Files
Removesmanage.com/subscribe?
a select file With VueJS
user Axios progress-indicator-with-axios-and-vuejs/)
has anduploaded
- Server Side Up

uploading- API
*/ u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
removeFile( key ){
files-
this.files.splice( key, 1 );
App
vuejs- }Development?
axios/) } We're
} writing
a book
</script>
on API
Driven
App
There ya go! You can now allow users to
Development. adjust their mistakes if they
Be the
select afirst
fileto they don’t want to upload.
know
once it
is
Gotchas and Recommendations
ready!

A few things to point out when uploading using FormData .

Adding additional POST data to the Request


You can always include more information than just files with your post.
When you build your FormData you can add additional text or other
fields like this:

/*
Initialize the form data
*/
let formData = new FormData();

/*
Iteate over any file sent over appending the files
to the form data.
*/
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];

formData.append('files[' + i + ']', file);


}

/*
Additional POST Data
*/
formData.append('first_name', 'Dan');
formData.append('last_name', 'Pastori');

The first_name and last_name fields will be accessible on the server


just like a normal post request!
Want to Next

Arrays with FormData()


learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
20/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up
Now since
uploading- API we are configuring our request before we send it to the sever,
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files- arrays get accessed differently. You will either need to account for this
App
vuejs-
when building your FormData object. In VueJS, when working with
Development?
axios/) We're
arrays, writing
you can’t just do:
a book
on API
Driven
this.coolData = ['one', 'two', 'three'];
App
formData.append('cool_data', this.coolData);
Development.
Be the
or you will
first toget an [object Object] on the server side. You can either
know
iterate over
once it your cool data and push it on a nicely organized array or you
is
can do ready!
a JSON.stringify() method on the data which will convert it
to JSON before sending it to the server.

this.coolData = ['one', 'two', 'three'];


formData.append('cool_data', JSON.stringify( this.coolData ) );

You will just need to decode it before you can access it. In PHP, that
method would be json_decode($json) .

Clearing local les on success


When axios returns success, another quick tip is to reset your local files
array back to nothing. This makes sure that if you are doing things in a
single page application type way or any AJAX driven way, the user who
initially submitted the files doesn’t try to re-send a different group of files
and gets the first group of files that still exist in the array sent along as
well. You can simply clear your local files like this:

this.files = '';

Conclusion
After running through this a few times, uploading files with VueJS and
Axios through AJAX becomes a little easier to grasp! Hopefully this
tutorial has helped a little. There is always room for expansion and you
can do Want
progress
to uploads and other cool features. Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
21/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
files-
This type of file uploading process comes in handy when developing an
Driven
App
vuejs-API Driven Application, especially when using VueJS. We are working on
Development?
axios/)
a book We're
that will tie in this feature along with a whole bunch more API
writing
Driven aon
book
ideals.
API We will go start to implementation to launch of an API
Driven
Driven App
Application and point out common gotchas and tips. Sign up here
Development.
to stay Be
in the
the loop as the book progresses: Server Side Up General List
first to
(https://serversideup.us2.list-manage.com/subscribe?
know
once it
u=a27137fc57d223f1cc7b986db&id=1276f15943)
is
ready!

ABOUT THE AUTHOR

Builder, creator, and maker. Dan Pastori has over 10 years experience as a full stack
developer. When you aren't nding Dan working on building a farm using Arduinos, catch
him at the beach or hiking in the National Parks.
Follow me on Twitter (https://twitter.com/danpastori)

Related Stories

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
22/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files-
App
vuejs- Development?
axios/) We're
writing
a book
on API
Driven
App
Development.
Be the
first to
know
once it
is
ready!

(https://serversideup.net/how-to-preload-css-background-images/)

How to Preload CSS Background Images


(https://serversideup.net/how-to-preload-css-background-images/)
Add the preload of background images through CSS to improve your AmplitudeJS player’s UX and
get rid of the ash on initial load.

Dan Pastori
3 months ago · AmplitudeJS (/search/?type=tutorials&tags=amplitudejs)

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
23/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files-
App
vuejs- Development?
axios/) We're
writing
a book
on API
Driven
App
Development.
Be the
first to
know
once it
is
ready!

(https://serversideup.net/sorting-in-vuejs-components-and-vuex-state/)

Sorting in VueJS Components and Vuex State


(https://serversideup.net/sorting-in-vuejs-components-and-vuex-state/)
VueJS reactive properties make sorting data a breeze. We wil go through examples on how to sort
within a component and in a Vuex data store.

Dan Pastori
3 months ago · Vue (/search/?type=tutorials&tags=vue)

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
24/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files-
App
vuejs- Development?
axios/) We're
writing
a book
on API
Driven
App
Development.
Be the
first to
know
once it
is
ready!

(https://serversideup.net/amplitudejs-con guration-options/)

AmplitudeJS Con guration Options


(https://serversideup.net/amplitudejs-con guration-options/)
AmplitudeJS con guration helps you build a player tailored to your needs. We will be going through
a few of these options with examples.

Dan Pastori
3 months ago · AmplitudeJS (/search/?type=tutorials&tags=amplitudejs)

24 Comments Server Side Up 


1 Login

 Recommend 3 t Tweet f Share Sort by Oldest

Join the discussion…

LOG IN WITH OR SIGN UP WITH DISQUS ?

Name

Pim Hooghiemstra • a year ago


Very nicetotutorial Dan. Would be interesting to improve with both progress of the upload (as youNext
Want
mentioned)
learn and theGet Updates
possibility to show thumbnails ofFile
the Upload
files! Any ideas on
Progress this? with Axios and
Indicator
△ more ▽ • Reply (https://serversideup.us2.list-
• Share ›
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
25/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API Dan Pastori Mod > Pim Hooghiemstra • a year ago
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files- Hi @Pim Hooghiemstra ! Thanks for the kind words! I'm working on a tutorial on how to
App
vuejs- do that now. You can do it with the FileReader API: https://developer.mozilla.o... I'll be
Development?
axios/) We're
going a little more in depth and doing progress and combining it all together, but that
should help for now
writing
a book1 △ ▽ • Reply • Share ›
on API
Driven
App Jean Gérard Bousiquot > Dan Pastori • a year ago
Development.Nice tutorial! I was going to ask for the same thing. Progress bar with Axios.
Be the
first to Can't wait for the follow up tuts. Thanks!
know 1 △ ▽ • Reply • Share ›
once it
is
ready! Dan Pastori Mod > Jean Gérard Bousiquot • a year ago
@Jean Gérard Bousiquot Just posted the progress bar tutorial as a part
of the series on file uploading. Let me know if this helps:
https://serversideup.net/yo...
1△ ▽ • Reply • Share ›

Jean Gérard Bousiquot > Dan Pastori • a year ago


Awww, thanks! I'm going to have a look at it now. I'll you know how it
goes. Again thanks for your work!
△ ▽ • Reply • Share ›

Dan Pastori Mod > Pim Hooghiemstra • a year ago


Hi @Pim Hooghiemstra I just released the next tutorials that goes through the progress
upload and the thumbnail previews. Check em out here: https://serversideup.net/yo...
△ ▽ • Reply • Share ›

Pim Hooghiemstra > Dan Pastori • a year ago


Great! Will have a look at it and let you know!
△ ▽ • Reply • Share ›

Junaid Ahmad • a year ago


Great tutorial indeed.
△ ▽ • Reply • Share ›

Stacy • 10 months ago


Having an issue with the submit multiple files. Error is: {"statusCode":400,"error":"Bad
Request","message":"No file has been uploaded as part of this attachment."}

Single attachment works fine. I think it relates to how the formData is appending but not sure.
Any tips on this that may not be in this great tutorial?
△ ▽ • Reply • Share ›

Stacy > Stacy • 10 months ago


Here's the code I'm trying:
Want to Next
<template> Get Updates File Upload Progress Indicator with Axios and
learn
<div class="container"> VueJS (https://serversideup.net/file-upload-
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/ 26/30
<div class="large-12 medium-12 small-12 cell">
about
<div class= large-12 medium-12 small-12 cell >
Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
(https://serversideup.net/courses/guide-
03/01/2019
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files- <label>File
App
vuejs- <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
Development?
axios/) We're</label>
writing<button v-on:click="submitFile()">Submit</button>
a book
on API
Driven
App
Development.
Be the <label>Files
first to<input type="file" id="files" ref="files" multiple="" v-on:change="handleFilesUpload()"/>
know</label>
once it
is <button v-on:click="submitFiles()">Submit</button>
ready!
see more

△ ▽ • Reply • Share ›

Dan Pastori Mod > Stacy • 6 months ago


Hmmm this is interesting. Could you have some server side middleware that are
stripping files or moving them to a different global array? Or could it be stripping
the files from the request?
△ ▽ • Reply • Share ›

Frank Schneidewind • 9 months ago


Very nice tutorial, thank you very much!

However, i'm getting this error: "Cannot read property 'length' of undefined""
I think it has something to do with the for-loop but i don't know exactly what happened here.

Does anybody have an idea? Thank you very much!


△ ▽ • Reply • Share ›

Dan Pastori Mod > Frank Schneidewind • 6 months ago


So I'm iterating over the files array. This is scoped within the vue component. If you
don't have a local files array variable, this could be the issue. It's because it's saying
files is undefined.
△ ▽ • Reply • Share ›

shegun babs • 9 months ago


Amazing tutorial, exactly what I was looking for.
△ ▽ • Reply • Share ›

Jerson Moreno • 8 months ago


That's an excellent tutorial and very explained. Thank you!
△ ▽ • Reply • Share ›

forextor • 8 months ago


Love this tutorial... please keep sharing!...
Want to Next
△ ▽ • Reply • Share ›
Get Updates File Upload Progress Indicator with Axios and
learn
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
27/30
Dan Pastori > forextor • 6 months ago
Mod
Dan Pastori Mod > forextor 6 months ago
03/01/2019 about
(https://serversideup.net/courses/guide-
manage.com/subscribe?Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
- Server Side Up
API Thanks so much! I'll try to whip up some more!
uploading- u=a27137fc57d223f1cc7b986db&id=1276f15943)
△ ▽ • Reply • Share ›
Driven
files-
App
vuejs- Ranga • 6 months ago
Development?
axios/) We're
Getting Unsupported Media Type Error.
writing
a book
let formData = new FormData();
on API
formData.append('file',
Driven this.file);
App
console.log(formData);
Development.
varBe the
access_token = localStorage.getItem('access_token');
first to
varknow
config = {
headers:
once it {
is
'Content-Type': 'multipart/form-data',
ready!
'accept': 'application/json',
'X-APP-NAME':'falcon-admin',
'X-AUTH-TOKEN': access_token
}
};
axios.post('http://ec2-35-171-103-35.co...:8090/v1/parse/faq', config)
.then((response) => {
console.log(response);
if(response.status == 200)alert("Created");
// window.location = ('/index.html');
})
△ ▽ • Reply • Share ›

Dan Pastori Mod > Ranga • 6 months ago


Could this be due to an invalid file from ec2? I think this Is this a server side issue, could
it be some configuration there? Let me know and I can give you hand!
△ ▽ • Reply • Share ›

Ralph Toledo • 6 months ago


Very useful tutorial Dan. Thanks for this. I just want to inquire if any one is having problem with
the remove file on multiple items, when I tried to remove the first item it is always removing the
the last file and not the file I selected. It is behaving as expected when I started removing file
from the last item though.
△ ▽ • Reply • Share ›

Dan Pastori Mod > Ralph Toledo • 6 months ago


@Ralph Toledo What I'm thinking it could be is passing the wrong key. The remove file
method accepts a key for which index should be removed. In the tutorial this is set by
iterating over all of the files. Is this how you have it set up too or did you modify? If so,
let me know and I can help out!
△ ▽ • Reply • Share ›

Billal BEGUERADJ • 2 days ago


Good tutorial.
Want Next
I can nottoupload a single image using the first method you described here. I always get an
Get Updates
learnobject on the server side. File Upload Progress Indicator with Axios and
empty
more (https://serversideup.us2.list- VueJS (https://serversideup.net/file-upload-
△ ▽ • Reply • Share ›
https://serversideup.net/uploading-files-vuejs-axios/ 28/30
△ ▽ py
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Dan Pastori Mod > Billal BEGUERADJ • 12 hours ago
Driven
files-
App @Billal BEGUERADJ The most important thing to add to your POST request are the
vuejs- headers:
Development?
axios/) We're{
writing
headers: {
a book
on API
'Content-Type': 'multipart/form-data'
Driven}
App }
Development.
Be theThis ensures that you will have something being passed for files. Did you add that?
first to
know1 △ ▽ • Reply • Share ›
once it
is Billal BEGUERADJ > Dan Pastori • 12 hours ago
ready!
Yes,in fact my issue was on the server side :) Thank you for sharing.
△ ▽ • Reply • Share ›

ALSO ON SERVER SIDE UP

Drag and Drop File Uploads with VueJS and Using SASS in Vue Components with
Axios - Server Side Up Laravel Mix - Server Side Up
11 comments • a year ago 2 comments • a year ago
Dan Pastori — Roberto Munhoz Are you Dan Pastori — Jacinto Joao thanks for pointing
passing in the key of the file in the array to the this out! We ran into an issue on a few other
remove function? That will remove the right file. projects similar that was due to a node …

Google Analytics with Vue Router in an SPA Vue JS Tag input - Server Side Up
- Server Side Up 1 comment • a year ago
5 comments • a year ago chenlee — It seems that this tutorial's order is
cicnavi — Great, thank you! not right.

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd Disqus' Privacy PolicyPrivacy PolicyPrivacy

(/)
Tutorials and resources for people who love technology.
SIGNUP FOR UPDATES

Your Email Subscribe

Courses Tutorials
Want to (/search/? (/search/? Next
learn Get Home (/)
Updates type=courses) type=tutorials)
File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
29/30
03/01/2019 about
(https://serversideup.net/courses/guide- Uploading Files With VueJS and Axios progress-indicator-with-axios-and-vuejs/)
manage.com/subscribe? - Server Side Up

uploading- API
u=a27137fc57d223f1cc7b986db&id=1276f15943)
Driven
files-
App
vuejs- Development?
axios/) We're
writing
(https://twitter.com/serversideup)
(https://github.com/serversideup)
(https://www.facebook.com/serversideup)
a book
on API
Driven
AppServer Side Up
Copyright ® 2019
Development.
Be the
first toHosted By Linode (https://www.linode.com/?r=5a1b585e4eb919d3d89ad242bd1bb2924754c444)
know
once it
is
ready!

Want to Next
learn Get Updates File Upload Progress Indicator with Axios and
more (https://serversideup.us2.list-
https://serversideup.net/uploading-files-vuejs-axios/
VueJS (https://serversideup.net/file-upload-
30/30

Das könnte Ihnen auch gefallen