How upload file PDF in Laravel Using Vue - laravel

I wanna get file pdf document from View use Vue to Laravel. But it still bug. Can help me what is wrong with my code?
This is my Blade
<template>
<form class="form" files="true" method="post" #submit.prevent="onSubmit" enctype="multipart/form-data">
<div class="form-group">
<label>File SK
<input type="file" multiple class="form-control-file" name="fileSk" id="fileSk" ref="fileSk"
#change="fileSkUpload()"/>
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</template>
This is my Vue Code for getting file
fileSkUpload(event) {
let files = event.target.files;
if (files.length) this.fileSk = files[0];
},
onSubmit() {
let data = new FormData();
data.append('fileSk', this.fileSK);
data.append('_method', 'put'); // add this
axios.post('/psu/list/store', {
data: this.data,
}).then(response => {
this.data = ''
}).catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
},
This is my Controller
public function store(Request $request)
{
$dokumen = new Dokumen();
$psu = new Psu();
$fileSk = $request->file('fileSk');
$data = $request->input('fileSk');
$extension = $fileSk->getClientOriginalExtension();
Storage::disk('uploads')->put($fileSk->getFileName() . '.' . $extension, File::get($file));
$dokumen->file_image_dokumen = $fileSk->getFileName() . '.' . $extension;
$dokumen->save();
}
I got this Error:
"Call to a member function getClientOriginalExtension() on null"
Error

In your controller you haven't initialised the $file variable.
Instead of using the Storage facade to store the file you can just use the Request itself:
$fileSk->storeAs('', $fileSk->getFileName() . '.' . $extension, 'uploads');
Storing uploaded files
You seem to have a few of issues in your JS code.
1. Don't include the parentheses in #change="fileSkUpload()" as this will cause the event not to be passed to the method:
#change="fileSkUpload"
alternatively you will have to pass the event yourself:
#change="fileSkUpload($event)"
$event docs
2. I noticed that in your fileSkUpload method you're referencing this.fileSk but in your onSubmit method you're referencing this.fileSK (capitalised K) - these should be the same.
3. You don't need to wrap the FormData in a object. Change your axios call to just be:
axios.post('/psu/list/store', data)
.then(response => {
this.data = ''
}).catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});

Related

I.m Getting "Call to a member function getClientOriginalName() on null" when uploading image with axios in laravel blade

Why I'm getting
Call to a member function getClientOriginalName() on null
when uploading an image as below.
Request payload is looks like
------WebKitFormBoundaryU2XJIVhmCHdi06EH
Content-Disposition: form-data; name="image"; filename="download (3).jfif"
Content-Type: image/jpeg
------WebKitFormBoundaryU2XJIVhmCHdi06EH--
in my blade file
<form action="" id="img_form" method="POST" enctype="multipart/form-data" onchange="uploadImage()">
#csrf
<input type="file" id="image" name="image" onchange="uploadImage()">
</form>
Js Code
function uploadImage(event) {
console.log('image');
const formData = new FormData();
const imagefile = document.querySelector('#image');
formData.append("image", imagefile.files[0])
// formData.append("image_2", imagefile.files[0]);
console.log('formdata' +formData);
axios.post('upload/image', formData, {
headers: {
'Content-Type': imagefile.type
// 'Content-Type': 'multipart/form-data;charset=utf-8;boundary=' + Math.random().toString().substr(2)
}
}).then(response => {
console.log('response' + response.data);
});
}
In My laravel Controller
public function uploadImage(Request $request){
$file = $request->file('image');
$name = $file->getClientOriginalName().'-'.time() ;
$filePath = 'images/' . $name;
Storage::disk('public')->put($filePath, file_get_contents($file));
$get_url = Storage::disk('public')->url($filePath);
return response()->json([
'name' => $name,
'url' => $get_url
]);
}
your request dosent have file as 'image_ad' , so use it:
$file = $request->file('image');

Uploading Multiple Image in Laravel and vue js

Am working on an app that should upload multiple images in the database using laravel and vue js.
Now for some reason it keeps on returning null value on the back end side. Hope someone can pin point the problem in this code.
this is my front-end code vue js
<template>
<div>
<div>
<form #submit.prevent="submit">
<input type="file" #change="onChange" multiple/>
<input type="submit" value="Upload">
</form>
</div>
</div>
</template>
<script>
export default {
data: ()=>({
image:[],
}),
methods:{
onChange(e){
this.image = e.target.files[0];
},
submit(){
let payload = new FormData();
for(let i=0; i<this.image.length; i++){
payload.append('image[]', this.image[i])
}
axios.post('/api/formsubmit',payload).then(res=>{
console.log("Response", res.data)
}).catch(err=>console.log(err))
}
},
}
</script>
and this is may back-end code Laravel 7
public function multipleupload(Request $request)
{
try{
if($request->hasFile('image')){
$upload = $request->file('image');
$file_name = time().'.'.$upload->getClientOriginalName();
$upload->move(public_path('image'), $file_name);
return response()->json([
'message'=>'File upload successfully!'
], 200);
}else {
return 'no data';
}
}catch(\Exception $e){
return response()->json([
'message'=>$e->getMessage()
]);
}
}
This code will always return 'no data'. been trying to figure it out but with no progress I hope someone can help.
Thanks,
if you want to upload multiple images you have to do loop, you can try this :
public function multipleupload(Request $request)
{
$input = $request->all();
request()->validate([
'image' => 'required',
]);
if($request->hasfile('image'))
{
foreach($request->file('image') as $image)
{
$imageName=file_name =$image->getClientOriginalName();
$image->move(public_path().'/images/', $imageName);
$insert['image'] = "$imageName";
}
}
Image::create($insert);
return back()
->with('success','Multiple Image Upload Successfully');
}

Laravel uploading file using vue3

i am trying to upload file in Laravel storage folder using vue3 composition API. i have added code but file is not being uploaded.
routes are correct, only null value is being added in mysql.
i have 3 columns in mysql database.
id | file_name | file_path
html
<input ref="file" v-on:change="handleFileUpload()" type="file" />
<button #click="senddata" class="">UPLOAD</button>
Vue function:
<script>
import axios from "axios";
import { defineComponent,ref } from 'vue'
export default defineComponent({
setup() {
const file = ref(null)
const handleFileUpload = async() => {
// debugger;
console.log("selected file",file.value.files)
//Upload to server
}
function senddata() {
axios.post('http://127.0.0.1:8000/api/store-files',{
file:this.file,
}).then(response=>{
message=response.data.message;
alert(message);
});
}
return {
senddata,
handleFileUpload,
file
};
}
})
</script>
Laravel Store Controller:
public function store(Request $request)
{
$file=new Files();
if($request->file()) {
$file=new Files();
$file_name = time().'_'.$request->file->getClientOriginalName();
$file_path = $request->file('file_link')->storeAs('uploads', $file_name, 'public');
$file->file_name = time().'_'.$request->file->getClientOriginalName();
$file->file_path = '/storage/' . $file_path;
$file->save();
return response()->json([
'message' => 'File added'
]);
}
}
you cannot send file in json, you need to send via FormData
you need to write code like
html
<input ref="file" v-on:change="handleFileUpload" type="file" />
<button #click="senddata" class="">UPLOAD</button>
Vue function
handleFileUpload() {
const file = ref(null)
this.file = file.value.files;
}
function senddata() {
let formData = new FormData();
formData.append('file',file)
axios.post('http://127.0.0.1:8000/api/store-files',formData).then(response=>{
message=response.data.message;
alert(message);
});
}
ref link https://developer.mozilla.org/en-US/docs/Web/API/FormData

Creating default object from empty value using laravel 6 and ajax

i have in an annonces table a multiple images, i want to update multiple images, but it gives me error:
Creating default object from empty value knowing that i tried to transform multipleimage to a given json.in the console it gives me the name of the images to select.
AnnoncesController.php
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::find($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$path = $request->images->store('annonces');
$Annonce->images = $path;
array_push($data,$path);
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
web.php
Route::post('annonces/filesUpdate','AnnoncesController#filesUpdate');
details.blade.php
<form method="post" action="{{url('annonces/filesUpdate')}}" enctype="multipart/form-data"
class="dropzone" id="dropzone">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 12,
renameFile: function(file) {
var dt = new Date();
var time = dt.getTime();
var images = time+file.name
console.log(time+file.name);
return images;
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
success: function(file, response)
{
console.log(response);
},
error: function(file, response)
{
return false;
}
};
</script>
You are not passing the id as route parameter in the form action so the $id value received in filesUptate method in controller will be null. You have to pass the $Annonce->id as route parameter via form action
//When you send this view as response from edit method you need to pass
//either $Annonce object or at least the $Annonce->id as $AnnonceId to the view
//If you pass the entire $Annonce object then append $Annonce->id as below
//to the form action or replace it with $AnnonceId if you are passing only
//$AnnonceId from the edit method of the controller
<form
method="post"
action="{{url('annonces/filesUpdate/' . $Annonce->id)}}"
enctype="multipart/form-data"
class="dropzone" id="dropzone"
>
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
</form>
The error probably arises as you are trying to call store method on array.
Try the below
public function filesUpdate(Request $request,$id)
{
$Annonce=Annonce::findOrFail($id);
$data = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
//Trying to call store on an array here
//$request->images is not an instance of UploadedFile
//$path = $request->images->store('annonces');
//$file is an instance of UploadedFile
//so you can call store method on it
$data[] = $file->store('annonces');
}
}
$Annonce->images = json_encode($data);
$Annonce->save();
return Redirect::to("annonces")
->withSuccess('Great! file has been successfully uploaded.');
}
You can also use $casts property to let Laravel handle the casting of images attribute automatically
class Annonce extends Model
{
protected $casts = [ 'images' => 'array'];
}

VueJs & Laravel. I can't send an excel file with Vuejs and FileReader

I would like to load an excel file to send it with axios to Controller and Maatwebsite\Excel for an Import.
The import part in Controller is working when i use Php from blade, i have a problem when sending from my Vuejs Component. I can't Read the Excel File. or Maybe i can't read it in Controller.
This is my code :
<template>
<input type="file" #change="checkFile" />
<button #click="importExcel()">Import File</button>
</template>
<script>
//In method
checkFile(e) {
var files = e.target.files || e.dataTransfer.files;
console.log('#', files); // The file is in console
if (!files.length)
return;
this.createFile(files[0]);
},
createFile(file) {
var reader = new FileReader();
var vm = this;
reader.readAsDataURL(file)
vm.ex.excel=file; // my ex.excel object contain File
},
importExcel: function () {
var formData = new FormData();
formData.append("file", this.ex.excel);
axios.post('/importExcel', formData)
},
</script>
So in Controller, i use this code when i'm using php (working)
public function importExcel(Request $request)
{
if($request->hasFile('import_file')){
Excel::import(new UsersImport, request()->file('import_file'));
}
return back();
}
When i try this code for axios. i have an error :
public function importExcel(Request $request)
{
Excel::import(new UsersImport, $request->excel);
return back();
}
Error: No ReaderType or WriterType could be detected
Console.log(file) in image
UPDATE: In controller i added
$a = $request->excel;
dd($a);
result in : null
<template>
<input type="file" ref="file" #change="checkFile" />
<button #click="importExcel()">Import File</button>
</template>
<script>
//In method
{
...
createFile(file) {
this.ex.excel = this.$refs.file.target.value.files[0]
}
...
}
</script>
<?php
...
public function importExcel(Request $request)
{
Excel::import(new UsersImport, $request->file('file'));
return back();
}
...
looks like the mime-type is missing, try add the mime-type together with your HTTP POST ...

Resources