How to convert base64 image to UploadedFile Laravel - laravel

Vue Version : 2.6.10
Laravel Version : 6.0
I am using this vue upload package and everything is ok on client side (at least I think so). But on the server side, where I am using the laravel, have some problem.
Here is my vue send method:
setImage: function (file) {
let formData = new FormData();
formData.append('file', file);
axios.post(upload_route, formData , {
headers: { 'Content-Type': 'multipart/form-data' }
})
.then(response => {
// upload successful
})
.catch(error => console.log(error));
},
And this is my server side method:
public function upload(Request $request){
$path = $request->file('file')->store('avatars');
return response('upload success' , 200);
}
When I upload the file to the server, it gives me this error:
"message": "Call to a member function store() on null",
The file object I am sending in the setImage function is something like this (if I log it with console.log):
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE...

I believe file parameter on setImage is not a File object. So the $request->file('file') is null, because you attach a string (base64), not a file.
You told us that output from console.log is base64 path, then you need to convert that (base64) to file.
Since you're using Laravel, here is the technique:
use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\File;
.....
$base64File = $request->input('file');
// decode the base64 file
$fileData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64File));
// save it to temporary dir first.
$tmpFilePath = sys_get_temp_dir() . '/' . Str::uuid()->toString();
file_put_contents($tmpFilePath, $fileData);
// this just to help us get file info.
$tmpFile = new File($tmpFilePath);
$file = new UploadedFile(
$tmpFile->getPathname(),
$tmpFile->getFilename(),
$tmpFile->getMimeType(),
0,
true // Mark it as test, since the file isn't from real HTTP POST.
);
$file->store('avatars');
Update
Since you're using vue-image-upload-resize, I check the documentation that it has built in function to change the output from base64 to blob, so you can just:
<image-uploader
...
output-format="blob"
... />

<?php
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
​
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('Image Type is Not valid');
}
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('Failed to Decode BASE64');
}
} else {
throw new \Exception('Data Not Matched With Image Data');
}
file_put_contents("image_name.{$type}", $data);//save decoded data as image
?>
This decode and preg_match always worked for me whenever i have image like
data:image/jpeg;base64
Pass this data as $data and your extension type as $type

Found better solution, when temp files deletes after script terminate
class FileHelper
{
public static function fromBase64(string $base64File): UploadedFile
{
// Get file data base64 string
$fileData = base64_decode(Arr::last(explode(',', $base64File)));
// Create temp file and get its absolute path
$tempFile = tmpfile();
$tempFilePath = stream_get_meta_data($tempFile)['uri'];
// Save file data in file
file_put_contents($tempFilePath, $fileData);
$tempFileObject = new File($tempFilePath);
$file = new UploadedFile(
$tempFileObject->getPathname(),
$tempFileObject->getFilename(),
$tempFileObject->getMimeType(),
0,
true // Mark it as test, since the file isn't from real HTTP POST.
);
// Close this file after response is sent.
// Closing the file will cause to remove it from temp director!
app()->terminating(function () use ($tempFile) {
fclose($tempFile);
});
// return UploadedFile object
return $file;
}
}
From https://gist.github.com/waska14/8b3bcebfad1f86f7fcd3b82927576e38

Related

Get image from blob Laravel vue

First of all, this is the start of where I am at as a similar post
Store blob as a file in S3 with Laravel
I am sending a photo from VueJS to Laravel. It is coming as multipart/form-data.
Vue Code:
export default {
emits: ['onClose'],
props: ['isOpen'],
data: function() {
return {
serverOptions: {
process: (fieldName, file, metadata, load, error) => {
const formData = new FormData();
formData.append(fieldName, file, file.name);
axios({
method: "POST",
url: '/chat/room/upload',
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
load();
})
.catch(() => {
error();
});
}
},
files: [],
};
},
methods: {
handleFilePondInit: function () {
console.log('FilePond has initialized');
// example of instance method call on pond reference
this.$refs.pond.getFiles();
console.log(this.$refs.pond.getFiles());
},
},
Laravel Controller:
public function uploadImage(Request $request)
{
// This is what this is SUPPOSED to do. Grab the file from the frontend
// Bring it here. Store it in S3, return the path with the CDN URL
// Then store that URL into the DB as a message. Once that is done, then
// Broadcast the message to said room.
if ($request->has('upload')) {
$files = $request->get('photo');
$urls = [];
foreach ($files as $file) {
$filename = 'files/' . $file['name'];
// Upload File to s3
Storage::disk('digitalocean')->put($filename, $file['blob']);
Storage::disk('digitalocean')->setVisibility($filename, 'public');
$url = Storage::disk('digitalocean')->url($filename);
$urls[] = $url;
}
return response()->json(['urls' => $urls]);
}
// broadcast(new NewChatMessage($newMessage))->toOthers();
// return $newMessage;
}
First: I want to state that if there is something wrong with the current code, just know its because ive been playing around with this for 3 hours now and been trying anything. I am sure at one point I had it close but somehow screwed it up along the way so I am more looking for fresh eyes to show me my error.
That being said, the other part to take into account is in DevTools under Network I can clearly see the blob and can load it up, I can also see the "upload" item and under there the form data which shows the following
------WebKitFormBoundary7qD7xdmiQO9U1Ko0
Content-Disposition: form-data; name="photo"; filename="6A8B48B4-F546-438E-852E-C24340525C20_1_201_a.jpeg"
Content-Type: image/jpeg
------WebKitFormBoundary7qD7xdmiQO9U1Ko0--
it clearly also shows photo: (binary) so I am completely confused as to what I am doing wrong. The ULTIMATE goal here is to get the image, store it as public in S3/DigitalOcean then grab the public URL to the file and store in the DB.
Any help would be GREATLY appreciated!

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

Unable to read filelist object in Laravel controller from vue

I'm creating an application where user is filing up a form with possibility to send multiple files along
In vue.js I'm creating formData with an array of files and with an object with the rest of inputs fields. I'm posting that with Axios.
In request in Laravel controller I can't access my filelist-object.
I can see the
$request->My_Array,
but I can read the data store inside
I have tried to use loops also I have try :
$request->all();
$request->file('files');
My input
<input class="browse" V-on::change="onImageChange" type="file">
My vue.js component
onImageChange(event) {
this.files.push(event.target.files);
},
submit(e) {
e.preventDefault();
let currentObj = this;
const fd = new FormData();
for (let i = 0; i < this.files.length; i++) {
fd.append('IoFiles[]', this.files[i]);
}
console.log(this.files);
fd.append('IoFiles', this.files);
fd.append('fields', JSON.stringify(this.fields));
axios.post('/io',
fd,
{headers: {'Content-Type': 'multipart/form-data'}})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
},
My Laravel controller
public function store(Request $request)
{
if ($request->IoFiles) {
$medias = $request->IoFiles;
foreach ($medias as $image) {
return $image->getClientOriginalName();//That give me an error
}
}
}
There are a couple of issues with your code.
Firstly, V-on::change="onImageChange" should be:
v-on:change="onImageChange"
Please note:
the lowercase v for v-on
the single :
Alternatively, you could write #change="onImageChange".
Secondly, event.target.files returns a FileList not a single file so you need to change your onImageChange code to the following be able to get the file itself:
onImageChange(event) {
this.files.push(event.target.files[0]); //Note the [0] after files
},

Laravel / vue-froala-wysiwyg integration

I'll like to implemente the image upload system within my Laravel/VueJS project but I can't find a right way to do so. How can I set up my Controller function in order to handle this upload?
Edit:
This is my Editor configuration:
config: {
imageUploadParam: 'imageFile',
imageUploadURL: '/froala/upload/image',
imageUploadMethod: 'POST',
imageMaxSize: 5 * 1024 * 1024,
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
}
And this is the function that handles the request:
public function uploadImage(Request $request)
{
$file = $request['imageFile'];
$name = $file->getClientOriginalName();
$name = strtolower(str_replace(' ', '', $name));
$path = $file->hashName();
$image = Image::make($file);
Storage::put("/threads/{$path}", (string) $image->encode());
$multimedia = Multimedia::create([
'name' => $name,
'path' => $path
]);
return ['link' => $multimedia->path];
}
I am using the Intervention Image library to handle the image upload.
Edit 2:
I'm getting an 419 error related with the csrf token. So, how can i pass it to the function? I know how to get it but using the imageUploadParams configuration of the editor is not working:
imageUploadParams: {
csrf: this.csrf
}
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
You need to pass the correct X-CSRF-TOKEN value to avoid the 419 error.
First check that you have the token defined the in the meta header with something like:
<meta name="csrf-token" content="{{ csrf_token() }}">
Early in your VueJS add:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
Then add the following to your Froala config section:
config: {
requestHeaders: {
'X-CSRF-TOKEN': csrf_token
},
Media files should now pass through to your media upload function in Laravel.
From the documentation :
When an image is inserted into the WYSIWYG HTML editor, a HTTP request is automatically done to the server.
The specific URL that the request will be made to can be specified using the imageUploadURL config option.
Setup your routes.php file to properly direct the request to your controller of choice :
Route::post('/upload', 'FilesController#store');
Then, in your controller you can handle the image upload like you would normally. The important part is that you return the path to the file after you've saved it.
The returned JSON needs to look like: { "link": "path/to/image.jpg" }
Here is an example of what that could look like :
public function store(){
$filepath = request()->file('file')->store('images', 'public');
return ['link' => $filepath];
}
Of course, feel free to do any kind of validation or processing that you need.
instand of
imageUploadParams: {
csrf: this.csrf
}
use this
imageUploadParams: {
_token: this.csrf
}
Check this out From Documentation

DOMPDF not downloading file when using AJAX

I'm trying to work with the BarryVdh/DOMPDF code in my Laravel project.
I made a page with a print button, with
Print
This is calling the controller function :
public function printFacturen(Request $request) {
$facturen = Factuur::all();
view()->share('facturen', $facturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
This is successfully downloading the PDF file.
My route is :
Route::get('/print-facturen', 'PrintController#printFacturen')->name('print_overzicht_facturen');
But, I need the content of a radio button to fill my PDF instead.
So I change my a href to
Print
I add a jQuery function :
$(".printbtn").click(function(e)
{
var option = $("input[name='factuur_selectie']:checked").val();
$.ajax({
type: 'POST',
url: 'print-facturen',
data: {"optionID": option}
})
});
And my controller is changed to
public function printFacturen(Request $request) {
$option = $request->get('optionID');
$facturen = Factuur::all();
$searchFacturen = new \Illuminate\Database\Eloquent\Collection();
foreach ($facturen as $factuur) {
if ($option == 1) {
$searchFacturen->add($factuur);
}
else if ($option == 2) {
if ($factuur->voldaan == true) {
$searchFacturen->add($factuur);
}
}
else if ($option == 3) {
if ($factuur->voldaan == false) {
$searchFacturen->add($factuur);
}
}
}
view()->share('facturen', $searchFacturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
I can see my optionID successfully, but the PDF file is NOT being downloaded anymore ... :-(
As I got a POST error, I added this route :
Route::post('/print-facturen', 'PrintController#printFacturen')->name('print_overzicht_facturen');
When inspecting the network, I see this :
SORRY, I'm not allowed yet to post pictures here :-(
(https://user-images.githubusercontent.com/5870500/32404394-3555952c-c14f-11e7-82c3-2d000d1a2661.png)
What am I doing wrong ?
Best regards,
Davy
You need to set proper http response headers:
header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
Other simple option to do it will be to dynamic modify link on radio click to get link like: example.org/download?radio=1

Resources