Vue upload file

Vue upload file DEFAULT

Before you can do that To complete this action, sign in to your Community account or create a new one.

Introduction

In this article, we will talk about how to handle file uploads with VueJs. We will create an images uploader that allow user to upload single or multiple images file by drag and drop or select file dialog.

We will then upload the selected images and display them accordingly. We will also learn to filter the upload file type, for example, we only allow images, do not allow file type like PDF.

Image uploader

File Upload UI & API

File upload consists of two parts: the UI (front-end) and the API (back-end). We will be using VueJs to handle the UI part. We need a backend application to accept the uploaded files. You may follow the backend tutorials or download and run either one of these server side application to handle file upload for your backend:-

We will be using File upload with Hapi.js as our backend throughout this articles. We will also learn the tricks to enable fake upload on the front-end.

Setup Project with Vue-Cli

We will be using vue-cli to scaffold Vue.js projects. We will be using the project template.

Alright, all set. Let’s proceed to create our component.

File Upload Component

We will write our code in . Remove all the auto-generated code in the file.

Notes:-

  1. Our component consists of 3 part: template (HTML), script (Javascript) and styles (SASS).
  2. Our template has an upload form.
  3. The form attribute is important. To enable file upload, this attribute must be set. Learn more about enctype here.
  4. We have a file input to accept file upload. The property indicate it’s allow multiple file upload. Remove it for single file upload.
  5. We will handle the file input event. Whenever the file input change (someone drop or select files), we will trigger the function and pass in the control name and selected files , and then upload to server.
  6. We limit the file input to accept images only with the attribute .
  7. The file input will be disabled during upload, so user can only drop / select files again after upload complete.
  8. We capture the of the when file changes. We use the variable in displaying number of files uploading .

Style our File Upload Component

Now, that’s the interesting part. Currently, our component look like this:

File upload component without styling

We need to transform it to look like this:

File upload component with styling

Let’s style it!

With only few lines of scss, our component looks prettier now.

Notes:-

  1. We make the file input invisible by applying style. This doesn’t hide the file input, it just make it invisible.
  2. Then, we style the file input parent element, the css class. We make it look like a drop file zone surround with dash.
  3. Then, we align the text inside dropbox to center.

File Upload Component Code

Let’s proceed to code our component.

Notes:-

  1. Our component will have a few statuses: STATUSINITIAL, STATUSSAVING, STATUSSUCCESS, STATUSFAILED, the variable name is pretty expressive themselves.
  2. Later on, we will call the Hapi.js file upload API to upload images, the API accept a field call . That’s our file input field name.
  3. We handle the file changes with the function. is an object returned by the files property of the HTML <input> element. It allow us to access the list of files selected with the <input type=“file”> element. Learn more [here]((https://developer.mozilla.org/en/docs/Web/API/FileList).
  4. We then create a new , and append all our files to it. interface provides a way to easily construct a set of key/value pairs representing form fields and their values. Learn more here.
  5. The function will call our file upload service (hang on, we will create the service next!). We also set the status according to the result.
  6. is the vue component life cycle hook. During that point, we will set our component status to initial state.

File Upload Service

Let’s proceed to create our service. We will be using axios to make HTTP calls.

Install axios

Service

Nothing much, the code is pretty expressive itself. We upload the files, wait for the result, map it accordingly.

You may run the application now with command. Try uploading a couple of images, and it’s working! (Remember to start your backend server)

Display Success and Failed Result

We can upload the files successfully now. However, there’s no indication in UI. Let’s update our HTML template.

Notes:-

  1. Display the uploaded image when upload successfully.
  2. Display the error message when upload failed.

Fake the Upload in Front-end

If you are lazy to start the back-end application (Hapi, Express, etc) to handle file upload. Here is a fake service to replace the file upload service.

Came across this solution in this Stackoverflow post. Pretty useful. My online demo is using this service.

Basically, what the code do is read the source, draw it in canvas, and save it as data url with the canvas function. Learn more about canvas here.

Now you can swap the real service with the fake one.

Done! Stop your backend API, refresh your browser, you should see our app is still working, calling fake service instead.

Bonus: Delay Your Promises

Sometimes, you may want to delay the promises to see the state changes. In our case, the file upload may complete too fast. Let’s write a helper function for that.

Then, you can use it in your component

Conclusion

That’s it. This is how you can handle file upload without using any 3rd party libraries and plugins in Vue. It isn’t that hard right?

Happy coding!

The UI (Front-end)

The API (Back-end) Tutorials and Sourcode

Sours: https://www.digitalocean.com/community/tutorials/how-to-handle-file-uploads-in-vue-2

vue-upload-component

npmnpmlicensegzip

Vue.js file upload component The component is just a button

https://lian-yue.github.io/vue-upload-component/

npm install vue-upload-component --save

Vue3

npm install [email protected] --save

https://lian-yue.github.io/vue-upload-component/#/documents

Vue.js 文件上传组件 组件只是一个按钮

https://lian-yue.github.io/vue-upload-component/#/zh-cn/

npm install vue-upload-component --save

Vue3

npm install [email protected] --save

https://lian-yue.github.io/vue-upload-component/#/zh-cn/documents

Sours: https://github.com/lian-yue/vue-upload-component
  1. Gtx 3060 benchmark
  2. Animal crossing plush
  3. Kitchenaid dishwasher instructions
  4. Hush puppies boots
  5. Geometric wristband tattoo

Upload

A collection of 27 posts

A tool for share files quickly build with Vue 3
Upload

A tool for share files quickly build with Vue 3

Easy way to upload and share files quickly for free and no login required.
16 May 2021
Complete and simple file uploader with image compressor
Upload

Complete and simple file uploader with image compressor

Complete and simple file uploader with image compressor in Vue.js.
27 June 2020
A little image uploader component for Vue
Upload

A little image uploader component for Vue

Vue component to upload images to rokka.io.
09 November 2019
A mobile vue component implementation for weui uploader
Upload

A mobile vue component implementation for weui uploader

a mobile vue component implementation for weui uploader.
25 August 2019
Vue Js fileuploader plugin to upload multiple files specially made for laravel
Upload

Vue Js fileuploader plugin to upload multiple files specially made for laravel

It's a vue js fileuploader plugin to handle multiple file upload specially made for laravel.
28 July 2019
A beautiful vue component for image cropping and uploading
Images

A beautiful vue component for image cropping and uploading

A beautiful vue component for image crop and upload.
30 December 2018
A simple vue-component for client-side image upload with resizing
Upload

A simple vue-component for client-side image upload with resizing

A Vue.js Plugin Component for client-side image upload with optional resizing and exif-based autorotate.
20 December 2018
Vue and Geo Simplifier
Upload

Vue and Geo Simplifier

You can insert your geojson or upload valid geojson file and simplify its geometry.
07 December 2018
A simple upload multiple image component for Vuejs
Upload

A simple upload multiple image component for Vuejs

A simple upload multiple image component for Vuejs.
11 October 2018
File upload component for Vue.js
Upload

File upload component for Vue.js

File upload component for Vue.js.
25 August 2018
Vue.js component for adding a file upload button for Vuetify
Upload

Vue.js component for adding a file upload button for Vuetify

This component is a file upload input with the base functionality of a Vuetify button.
21 August 2018
upload single/multi images and draw arrows
Upload

upload single/multi images and draw arrows

upload single/multi images, draw arrows, circle, lines, text and pen on images.
17 July 2018
A Vue2 plugin to make files upload simple and easier
Upload

A Vue2 plugin to make files upload simple and easier

A Vue2 plugin to make files upload simple and easier, you can drag files or select file in dialog to upload.
07 May 2018
A handy FilePond adapter component for Vue
Upload

A handy FilePond adapter component for Vue

Vue FilePond is a handy adapter component for FilePond, a JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user experience.
11 April 2018
A Vue.js upload component powered by simple-uploader.js
Upload

A Vue.js upload component powered by simple-uploader.js

A Vue.js upload component powered by simple-uploader.js.
24 November 2017
A Vue.js component for Dropzone.js - a drag’n’drop file uploads
Upload

A Vue.js component for Dropzone.js - a drag’n’drop file uploads

vue-dropzone A Vue component for file uploads, powered by Dropzone.js. Install // For Vue.js 2.0+ npm install [email protected]^2.0.0 You'll also need to load either the Material Icon or
17 August 2017
Drag and drop multiple file uploader with Vue.js v2 and Axios
Upload

Drag and drop multiple file uploader with Vue.js v2 and Axios

vue2-multi-uploader A drag and drop multiple file uploader component that uses Vue.js v2 and Axios. Uploader shows file names, sizes and total size of files added. It also allows setting a minimum
17 August 2017
Simple File upload component for Vue.js
Upload

Simple File upload component for Vue.js

vue-simple-upload An simple file upload component for vue.js. Installation npm install vue-simple-upload Usage vue-simple-upload is a UMD module, which can be used as a module in both CommonJS and AMD modular environments.
17 August 2017
Simple and hackable file uploader for Vue 2
Upload

Simple and hackable file uploader for Vue 2

Vue clip Vue clip is a minimalistic and hackable file uploader for VueJs. I wrote this plugin due to the absence of well written file uploaders with fine-grained controls. Features Written in vanilla
15 August 2017
A simple file upload component for vue
Upload

A simple file upload component for vue

A simple file upload component for vue A file upload component for vuejs. Live demo https://dai-siki.github.io/vue-upload-file/example/demo.html GitHub
08 June 2017
Vue.js file upload Support for multiple file uploads
Upload

Vue.js file upload Support for multiple file uploads

vue-upload-component Vue.js file upload component, Support for multiple file uploads, progress, html4, ie9 Html4 does not support the progress bar, file size, accept, timeout, headers, response status code error of judgment live
08 June 2017
A Vue component for file uploads
Upload

A Vue component for file uploads

A Vue component for file uploads A Vue.js component for Dropzone.js - a drag’n’drop file uploads utility with image previews. Live demo https://rowanwins.github.io/vue-dropzone/dist/index.
08 June 2017
Instagram filter Built with Vue.js
Images

Instagram filter Built with Vue.js

Instagram filter Rapid prototype Rapid prototype of the Instagram filter selection UX. Built with: Vue, Tachyons, CSSgram, Flickity. codepen demo See the Pen Instagram Filter Rapid Prototype (Vue + CSSGram) by Matt Rothenberg (@mattrothenberg)
02 June 2017
a vue plugin for image to crop and upload
Upload

a vue plugin for image to crop and upload

Vue-Core-Image-Upload a vue plugin for image upload and crop ( Support :iphone: IE9+) GitHub
26 September 2016
Magic upload image base on Vue.js Support paste and drag-drop
Upload

Magic upload image base on Vue.js Support paste and drag-drop

magic-upload-image magic upload image base on Vue.js Support paste, drag-drop, form -- Github issues like live demo http://upload.leanapp.cn/ GitHub
17 August 2016
A simple file upload component for Vue.js
Upload

A simple file upload component for Vue.js

A simple file upload component for Vue.js. Emits events for XHR Upload Progress for nice progress bars. vue-file-upload-component A simple file upload component for Vue.js. Emits events for XHR Upload Progress
17 August 2016
Sours: https://vuejsexamples.com/tag/upload/

Vue File Upload example using Axios

In this tutorial, I will show you way to build a Vue File Upload example that uses Axios and Multipart File for making HTTP requests. You will also know how to add Bootstrap progress bar, show response message and display list of files’ information (with url).

More Practice:
– Vue upload Image using Axios (with Preview)
– Vue Multiple Files Upload with Axios, FormData and Progress Bars
– Vue.js 2 CRUD Application with Vue Router & Axios
– Vue.js JWT Authentication with Vuex and Vue Router
– Vue Pagination with Axios and API example

Using Vuetify: Vuetify File Upload example

Contents

Overview

We’re gonna create a Vue File upload application in that user can:

  • see the upload process (percentage)
  • view all uploaded files
  • link to the file when clicking on the file name

vue-axios-file-upload-example-demo

Here are APIs that we will use Axios to make HTTP requests:

MethodsUrlsActions
POST/uploadupload a File
GET/filesget List of Files (name & url)
GET/files/[filename]download a File

You can find how to implement the Rest APIs Server at one of following posts:
– Node.js Express File Upload Rest API example
– Node.js Express File Upload to Google Cloud Storage example
– Spring Boot Multipart File upload (to static folder) example

Or: Spring Boot Multipart File upload (to database) example

Technology

  • Vue 2.6
  • Axios 0.19.2
  • Bootstrap 4

Setup Vue File Upload Project

Open cmd at the folder you want to save Project folder, run command:

You will see some options, choose default (babel, eslint).

Then we add Axios library with command: .

Structure the Project

After the process is done. We create new folders and files like this:

vue-axios-file-upload-example-project-structure

UploadFilesService provides methods to save File and get Files using Axios.
UploadFiles component contains upload form, progress bar, display of list files.
App.vue is the container that we embed all Vue components.

index.html for importing the Bootstrap.
http-common.js initializes Axios with HTTP base Url and headers.
– We configure port for our App in vue.config.js

Add Bootstrap to the project

Open index.html and add following line into tag:

Initialize Axios for Vue HTTP Client

Under src folder, we create http-common.js file like this:

Remember to change the , it depends on REST APIs url that your Server configures.

Create Service for Upload Files

This service will use Axios to send HTTP requests.
There are 2 functions:

  • : POST form data with a callback for tracking upload progress
  • : GET list of Files’ information

services/UploadFilesService.js

– First we import Axios as from http-common.js.

– is a data structure that can be used to store key-value pairs. We use it to build an object which corresponds to an HTML form with method.

– We pass to exposes progress events. This progress event are expensive (change detection for each event), so you should only use when you want to monitor it.

– We call the & method of to send an HTTP POST & Get request to the File Upload server.

Create Component for Upload Files

Let’s create a File Upload UI with Progress Bar, Card, Button and Message.

First we create a Vue component template and import :

components/UploadFiles.vue

Then we define the some variables inside

Next we define method which helps us to get the selected Files from element in HTML template later.

We also define method for upload file:

We use for accessing current File as the first Item. Then we call method on the with a callback.

The progress will be calculated basing on and .
If the transmission is done, we call to get the files’ information and assign the result to variable.

Here, is an array of objects.

We also need to do this work in method:

Now we implement the HTML template of the Upload File UI. Add the following content to :

In the code above, we use Bootstrap Progress Bar:

  • as a wrapper
  • inner to indicate the progress
  • requires to set the width by percentage
  • also requires and some aria attributes to make it accessible
  • Labels to progress bar is the text within it

Add Upload File Component to App Component

Open App.vue and embed the Component with tag.

Configure Port for Vue File Upload App

Because most of HTTP Server use CORS configuration that accepts resource sharing restricted to some sites or ports. And if you use the Project in this post for making Server, you need to configure port for our App.

In folder, create vue.config.js file with following content:

We’ve set our app running at port . vue.config.js will be automatically loaded by .

Run the App

Run this Vue File Upload App with command: .

Open Browser with url and check the result.

Further Reading

Fullstack CRUD App:

Conclusion

Today we’re learned how to build an example for upload Files using Vue and Axios. We also provide the ability to show list of files, upload progress with Bootstrap, and to download file from the server.

You can find how to implement the Rest APIs Server at one of following posts:
– Node.js Express File Upload Rest API example
– Node.js Express File Upload to Google Cloud Storage example
– Spring Boot Multipart File upload (to static folder) example

Or: Spring Boot Multipart File upload (to database) example

If you want to upload multiple files like this:

vue-js-multiple-file-upload-axios-formdata-progress-bar

Please visit:
Vue Multiple Files Upload with Axios, FormData and Progress Bars

Or use Vuetify for File Upload with the tutorial:
Vuetify File Upload example

Or Image upload:
Vue upload image using Axios (with Preview)

Source code

The source code for this Vue Client is uploaded to Github.

Sours: https://www.bezkoder.com/vue-axios-file-upload/

File vue upload

Form File Input

<template><div><b-form-filev-model="file1":state="Boolean(file1)"placeholder="Choose a file or drop it here..."drop-placeholder="Drop file here..." ></b-form-file><divclass="mt-3">Selected file: {{ file1 ? file1.name : '' }}</div><b-form-filev-model="file2"class="mt-3"plain></b-form-file><divclass="mt-3">Selected file: {{ file2 ? file2.name : '' }}</div></div></template><script>exportdefault { data() { return { file1: null, file2: null } } } </script>

For cross browser consistency, defaults to the Bootstrap custom file input to replace the browser defaults. They're built on top of semantic and accessible markup, so it is a solid replacement for the default file input.

Single file (default)

On single file mode, when no file is selected or user cancels the "Browse" dialog, is indicating no file selected. When a file is selected the return value will be a JavaScript object instance.

Multiple files

Multiple file uploading is supported by adding prop to component. In this case is always an . When no files are selected, an empty array will be returned. When a file or files are selected the return value will be an array of JavaScript object instances.

Directory mode

CAUTION: Directory mode is a non-standard feature. While being supported by all modern browsers, it should not be relied on for production. Read more on MDN and Can I use.

By adding the prop, a user can select directories instead of files. When a directory is selected, the directory and its entire hierarchy of contents are included in the set of selected items.

When in mode, files are returned in a nested array format by default. i.e.

dirA/ - fileA1 - fileA2 - dirB/ - fileB1 - dirC/ - fileC1 - fileC2 dirD/ - fileD1

will be returned as (or similar, file/directory order may vary):

[[fileA1, fileA2, [fileB1], [fileC1, fileC2]], [fileD1]]

If you set the prop, the array will be flattened:

[fileA1, fileA2, fileB1, fileC1, fileC2, fileD1]

Each file entry will have a special prop that will contain the relative path of each file. For nested directory structures, BootstrapVue uses its own routine to determine the relative path, otherwise it relies on .

Directory mode is also supported when the file input is in mode on most modern browsers.

Drag and Drop support

Drop mode is enabled by default. It can disabled by setting the prop. has no effect in mode (some browsers support dropping files onto a plain input file).

You can optionally set a different placeholder while dragging via the prop or the scoped slot. The prop only supports plain text. Use the slot for custom HTML markup. The slot takes precedence over the prop. The prop/slot has no effect if is set or in mode.

Note that native browser constraints (such as ) will not work with drop mode, as the hidden file input does not handle the drag and drop functionality and will have zero files selected.

Limiting to certain file types

You can limit the file types by setting the prop to a string containing the allowed file type(s). To specify more than one type, separate the values with a comma.

<div><b-form-fileaccept="image/*"></b-form-file><b-form-fileaccept="image/jpeg, image/png, image/gif"></b-form-file><b-form-fileaccept=".jpg, .png, .gif"></b-form-file></div>

To accept any file type, leave as (default). You can mix and match IANA media types and extensions.

Refer to IANA Media Types for a complete list of standard media types.

Note: Not all browsers support or respect the attribute on file inputs.

For drag and drop, BootstrapVue uses an internal file type checking routine and will filter out files that do not have the correct IANA media type or extension.

Customizing

, when not in mode, provides several features for customizing its appearance.

Control sizing

Use the prop to control the visual size of the input. The default size is considered (medium). Optional sizes are (large) and (small). These sizes line up with the sizes available on other form controls.

<div><b-form-grouplabel="Small:"label-cols-sm="2"label-size="sm"><b-form-fileid="file-small"size="sm"></b-form-file></b-form-group><b-form-grouplabel="Default:"label-cols-sm="2"><b-form-fileid="file-default"></b-form-file></b-form-group><b-form-grouplabel="Large:"label-cols-sm="2"label-size="lg"><b-form-fileid="file-large"size="lg"></b-form-file></b-form-group></div>

Note: Bootstrap v4.x does not natively support sizes for the custom file control. However, BootstrapVue includes custom SCSS/CSS that adds support for sizing the custom file input control.

Customize the placeholder text

Use the prop or the scoped slot to change the prompt text that is shown when no files are selected. The prop only supports plain text. Use the slot for custom HTML markup. The slot takes precedence over the prop.

Customize browse button label

If you want to globally change label, you can add something like this to your global stylesheets. Also it is advised to use :lang() for multi-language sites.

.custom-file-input:lang(en) ~ .custom-file-label::after { content: 'Browse'; }

Alternatively you can set the content of the custom file browse button text via the prop. Note, only plain text is supported. HTML and components are not supported.

File name formatter function

Set the prop to a function that accepts three arguments:

ArgumentTypeDescription
[1] ArrayFlat array of objects
[2] ArrayArray of arrays of objects when in mode
[3] ArrayFlat array of file names (strings)

The function should return a single formatted string (HTML is not supported). The formatter will not be called if no files are selected.

<template><b-form-filemultiple:file-name-formatter="formatNames"></b-form-file></template><script>exportdefault { methods: { formatNames(files) { return files.length === 1 ? files[0].name : `${files.length} files selected` } } } </script>

File name formatting via scoped slot

Alternatively, you can use the scoped slot to render the file names. The scoped slot will receive the following properties:

PropertyTypeDescription
ArrayFlat array of objects
ArrayArray of arrays of objects when in mode
ArrayFlat array of file names (strings)

All three properties are always arrays, regardless of the setting of the prop.

<template><b-form-filemultiple><templateslot="file-name"slot-scope="{ names }"><b-badgevariant="dark">{{ names[0] }}</b-badge><b-badgev-if="names.length > 1"variant="dark"class="ml-1"> + {{ names.length - 1 }} More files </b-badge></template></b-form-file></template>

When using the slot, the prop is ignored. The slot will not be rendered when there are no file(s) selected.

Non custom file input

You can have render a browser native file input by setting the prop. Note that many of the custom features do not apply when is set.

Contextual state feedback

Bootstrap includes validation styles for and states on most form controls.

Generally speaking, you'll want to use a particular state for specific types of feedback:

  • (denotes invalid state) is great for when there's a blocking or required field. A user must fill in this field properly to submit the form
  • (denotes valid state) is ideal for situations when you have per-field validation throughout a form and want to encourage a user through the rest of the fields
  • displays no validation state (neither valid nor invalid)

To apply one of the contextual state icons on , set the prop to (for invalid), (for valid), or (no validation state).

Note: Contextual states are not supported when in mode.

Autofocus

When the prop is set on , the input will be auto-focused when it is inserted (i.e. mounted) into the document, or re-activated when inside a Vue component. Note that this prop does not set the attribute on the input, nor can it tell when the input becomes visible.

Accessibility

When using the custom version of input which hides the original input, it is highly recommended that you supply a document unique ID string via the prop. This will automatically render the extra ARIA attributes required to improve usability for persons using assistive technologies.

Clearing the file selection

With inputs of type file, normally the is uni-directional (meaning you cannot pre-set the selected files). However, you can clear the file input's selected files by setting the to either (for single mode) or an empty array (for / mode).

Alternatively, provides a method that can be called to clear the file input. To take advantage of the method, you will need to obtain a reference to the component.

<template><div><b-form-filev-model="file"ref="file-input"class="mb-2"></b-form-file><b-button @click="clearFiles"class="mr-2">Reset via method</b-button><b-button @click="file = null">Reset via v-model</b-button><pclass="mt-2">Selected file: <b>{{ file ? file.name : '' }}</b></p></div></template><script>exportdefault { data() { return { file: null } }, methods: { clearFiles() { this.$refs['file-input'].reset() } } } </script>

Implementation notes

As not all browsers allow setting a value of a file input (even to or an empty string), employs a technique that works cross-browser that involves changing the input type to and then immediately back to type .

Nested file structures in mode require support in the browser. If targeting your app for older browsers, such as IE 11, please include a polyfill that provides support. If support is not detected, files will always be in a flat file structure.

Due to a "bug" in Chromium, nested file structures in mode are currently only supported when directories are dropped on the file input. When selecting them via the "Browse" dialog they will always be in a flattened array structure. Mozilla implemented the behavior the same way as Chromium.

Sours: https://bootstrap-vue.org/docs/components/form-file
How to Upload File using Vue.js with PHP

VueJS and Axios GitHub – axios/axios: Promise based HTTP client for the browser and node.js work beautifully together for making HTTP requests. However, uploading files 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.

🚨 Update October, 14, 2021

I’ve went through and updated the code in this tutorial to be more efficient and up-to-date. The code has been tested in Vue 3.0 and Axios v0.21.1. I’ve also made a Github repo that contains all of the examples in this course. Feel free to head over there and download any of the components you wish to use!

Prerequisites

In this tutorial I’m going to be using Axios v0.21.1 and VueJS v3.0.0 for doing the file uploads. On the back end you can use the framework that you want, or language that you want. I’ll talk about using PHP/Laravel to process files and more or less pseudo-code the backend process. The biggest take aways will be how to do the uploading of the file with VueJS and Axios.

I’m also going to assume you are using a modern browser that supports the object: FormData – Web APIs | MDN. 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:

If you take a look at the I added a few attributes. The first is a attribute that gives this input a name. We can now access this input from within VueJS which we will in a second.

UPDATE 10/14/2021: Remove ref=”file”

Previously I had as a key piece of this code. You can do this without ref as well and I’ll make sure to explain how later on when we implement the method:

The next is the 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.

The last element in the simple form is a button that calls a method when clicked. This is where we will submit our file to the server and we will be implementing this method as well.

Handle User File Upload

The first thing we want to do is add the method to our object which will give us a starting point for implementation:

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 object: FileList – Web APIs | MDN which contains objects: File – Web APIs | MDN. The 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 method add:

Now we have something to set in our method! Let’s go back and add the following code to the method:

What this does is when the file has been changed, we set the local file variable to the first object in the on the . The refers to the attribute on the the . This makes it easily accessible within our component.

UPDATE 10/14/2021: Implementation without $refs

You can also implement this functionality without the by passing the to the method:

Submit To Server Through Axios

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

Now this is where we implement our request.

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

Next, what we will do is append the file to the . This is done through the method on the object: FormData.append() – Web APIs | MDN. What we are doing is essentially building a key-value pair to submit to the server like a standard POST request:

We just append the file variable that we have our data stored in. Now I’m not going to go into validations, but before we go any further, if you were to put this in production and the file needed to be added, I’d add a validation here to make sure the variable contains an actual file.

Now we can begin to make our request! We will be doing this through the method. If you look at their API (GitHub – axios/axios: Promise based HTTP client for the browser and node.js), you see the 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:

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 . The next parameter is a key-value store of the data we are passing. This is our which we built to have our file. The third parameter is probably the key to making this all work. This is adding the 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 . Without this header, the POST request will ignore the file.

Now with the rest of our request, we process a callback method on a successful request which can be used to display a notification and we process a callback on failure which can be used to alert the user of an unsuccessful upload.

On the server side, you can access the file through the key of which is the first parameter of the method.

In PHP it’d be: and in Laravel, you can use the facade and access it through and do whatever server side processing you need.

Our component used for testing looks like this:

Github Component

If you’d like a Vue 3 compatible component for a single file upload, check out the component on Github. Feel free to submit any updates you’d like!

The next section, we will handle multiple files. This isn’t anything super different, but I’ll point out the changes!

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:

Besides the attribute name change and the changing to , the most important attribute is we added to our . 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 :

Now we have a local variable to store our files to. We can now do our method:

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

UPDATE 10/14/2021: Without $refs

Similar to the single file component, you can upload multiple files without the $refs attribute. Your template should look like:

The method should also be implemented like this, with the being passed as the only parameter:

Implement submitFiles() method

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

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

Now, what we will do is loop over all of the files selected and add them to the array we are going to submit to the server. The array will be a key in the object we will be sending to the server:

We are now ready to send our files to the server through Axios:

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 which is the first parameter of the method.

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

Our component should look like:

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.

Github Component

We also created a Github component for handling multiple file uploads. This can be used in your apps and is compatible with Vue 3!

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 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:

Hide File Input

The first thing we will do is hide the actual file input. This is because we will be making a simple design interface to allow users to select the files they want. I just added a style tag that moves the input off of the screen. This is because it’s a security issue to trigger a click on the hidden file input.

Next, I added a button that triggers a click on the input:

So when this is clicked, we trigger a click on the file element. We need to implement the method in our Vue component like this:

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.

UPDATE 10/14/2021: Remove $refs

You can also remove the attribute when uploading multiple files as well. Just make sure your method looks like:

We will go through the above method more in the next section. Also, make sure your method looks like:

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:

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 variable:

We do this through a loop instead of pushing the entire chunk onto the array because otherwise we’d have groups based on what was selected. You can add validations here as well so the user doesn’t upload 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:

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 . 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: which is part of the individual file object. There’s more information in the object which is documented here: File – Web APIs | MDN

Next, we add a method which will remove the file from the file array. When the file is removed, the reactive nature of VueJS will update our listing.

Implement removeFile() Method

This method will remove the file from our uploaded files array. First, let’s add the method to our array:

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

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 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 method to our methods object:

Like the rest of the examples, let’s first create our object:

Now, let’s add all of the chosen files to the form data:

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

Now, we can run the method to submit the files to our endpoint:

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 which is the first parameter of the method.

When using Laravel and the facade, you can access the selected files the user has uploaded with the following method: . In straight up PHP it’d be . You can now do any processing you want!

Our component should look like:

There ya go! You can now allow users to adjust their mistakes if they select a file they don’t want to upload.

Github Component

Yup! We made another component that allows the user to edit their file uploads before submitting to the server. Check it out and let us know your thoughts!

Gotchas and Recommendations

A few things to point out when uploading using .

Adding additional POST data to the Request

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

The and fields will be accessible on the server just like a normal post request!

Arrays with FormData()

Now since we are configuring our request before we send it to the sever, arrays get accessed differently. You will either need to account for this when building your object. In VueJS, when working with arrays, you can’t just do:

or you will get an on the server side. You can either iterate over your cool data and push it on a nicely organized array or you can do a method on the data which will convert it to JSON before sending it to the server.

You will just need to decode it before you can access it. In PHP, that method would be .

Clearing local files 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:

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 progress uploads and other cool features.

This type of file uploading process comes in handy when developing an API Driven Application, especially when using VueJS. We are working on a book that will tie in this feature along with a whole bunch more API Driven ideals. We will go start to implementation to launch of an API Driven Application and point out common gotchas and tips. Sign up here to stay in the loop as the book progresses: Server Side Up General List

Sours: https://serversideup.net/uploading-files-vuejs-axios/

You will also be interested:

The girl gently sat down on her knee and groped with one hand the member of Kostya, already ready for battle. She ran the soap over him. Rubbed his palms, then went down to his feet. Alena caught herself thinking that everything that is happening to her now begins to like her.



1430 1431 1432 1433 1434