Laravel-Vue: How to upload file

Laravel-Vue: How to upload file

In developing application, file upload is the most common feature. We will disccus the process of uploading file at ease.

Objective:

  • Upload file into the backend storage location.

Requirements: 

  • Laravel
  • Vue 2
  • Axios npm package

Procedures:

Vue

  • We will create a Upload.vue file and set our upload form. We have a file input and set its ref "fileAttachUpload" attribute. The input file was not displayed on page. We will call this on the button which we will setup next.
<input
type="file"
@change="onFilesSelected($event)"
ref="fileAttachUpload"
width="100%"
accept="application/pdf,image/*"
style="display: none;"
/>
  • We will create a button on current vue page that will trigger the fileAttachUpload ref atrribute we previously defined.
<v-btn
@click="$refs.fileAttachUpload.click()"
>
mdi-upload
  • Let set our data
data() {
selectedFiles: [],
}
  • Now, we go to our onFilesSelected method. 
onFilesSelected(event) {
this.selectedFiles = event.target.files
if (this.payment.id) {
Axios.post(`/upload`, this.prepareData())
}
},
  • The prepareData will set our uploaded files selected by user
prepareData(){
let formData = new FormData();
if(this.selectedFiles) {
for(var i=0; i < this.selectedFiles.length; i++){
let file = this.selectedFiles[i]
formData.append('files['+ i +']', file)
}
}
return formData
},

Laravel

Route

Route::post("/upload", "UploadController@uploadFile);

Controller

php artisan make:controller UploadController



The uploadFile method will handle our files and store it to our "storage/app/public/files" directory.

public function uploadFile(Request $request)
{

$files = $request->file('files');
if(count($files)){
foreach($files as $file){
$filename = Str::lower( Str::ascii($file->getClientOriginalName()) );
$path = $file->storeAs('./public/files/', $filename);
}
}
}
Thats it. Hope it helps web dev starters.