How to receive blob in Laravel API from the front end - laravel

I am sending blob PDF generated by JSPDF to Laravel API from the front end, but Laravel doesn't seeing it and saying the the field is required, when I console.log() the blob I see that it exists as bellow
Blob
size: 2888211
type: "application/pdf"
[[Prototype]]: Blob
the code in Laravel to store it
$report = $request->file('report');
$ext = $report->getClientOriginalExtension();
$report_name = $request->qr_url . ".$ext";
$report->move(public_path('uploads/reports/'), $report_name);
What is the wrong here please?

Why ?
just send them as files
let reader = new FileReader();
reader.addEventListener('load', (event) => {
// send that file
let file = event.target.result;
let formData = new FormData();
formData.append('file', file);
let request = new XMLHttpRequest();
request.open("POST", "endpoint url");
request.send(formData);
});
reader.readAsDataURL(blob);

Related

React Native Image File to base64 / blob

This is my react native version
react-native-cli: 2.0.1
react-native: 0.63.4
can please someone help ? I tried so many things to change my file from mobile device to send it as base64 or blob to server
But none can change my file to base 64 or blob
here's how my console logh : path : look like
file:///storage/emulated/0/DCIM/b01f3aef-4b56-48d9-b7a2-e3424df0f054.jpg --------IMAGEURI
yes thats an image uri and I can show it up on my mobile screen just by calling
<Image uri={that file path...}/>
for (var i = 0 ; i < entriesImage.length ; i++){
IdImage = [i][0]
LabelImage = entriesImage[i][0]
ImageUri = entriesImage[i][1].uri
Notes = entriesImage[i][1].notes
Latitude = entriesImage[i][1].location.latitude
Longitude = entriesImage[i][1].location.longitude
//DateImage = entriesImage[i][1].date
DateImage = new Date()
console.log(ImageUri,'--------IMAGEURI')
objImage = {
"surveyId": "3",
"photo": entriesImage[i][1].uri,
"photoId": [i][0],
"label": entriesImage[i][0],
"latitude": entriesImage[i][1].location.latitude,
"longitude": entriesImage[i][1].location.longitude,
"photoDate": DateImage,
"notes": Notes
}
arrayImage.push(objImage)
}
console.log(ImageUri,'--------IMAGEURI'), ImageUri as filepath I wanted to send to server
but still no luck on how to convert to to base64 or blob
I also tried expo image manipulator , also no luck , help please
Create a formData and use it like this to send to server
Create a function
const CreateFormData = (filePath) => {
var formdata = new FormData();
formdata.append('file', {
name: 'SampleImage.jpg',
uri: filePath, // File path
type: 'image/jpg',
});
return formdata;
};
Now use it like this
const response = CreateFormData("file:///storage/emulated/0/DCIM/b01f3aef-4b56-48d9-b7a2-e3424df0f054.jpg")
Now perform a POST request with this response formData in body

Expo React Native upload an image to Laravel in backend

I am fairly new to coding and I'm in the learning phase for both React Native and Laravel. I was working on some practice project and I needed to upload an image from my React Native app to the Laravel server and from the server I could save it on a cloud or something. I can upload and display the image on the app using expo-image-picker but I just can't seem to get it to post it to the server using formData.
Also, why is that when I console.log formData why is it showing an empty object?
My code to loading the image and uploading it:
pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if(!result.cancelled)
{
this.setState({
image : result.uri
})
}
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = result.uri;
//console.log("localUri:", localUri)
let filename = localUri.split('/').pop();
console.log("filename:", filename)
// extract the filetype
//let fileType = localUri.substring(localUri.lastIndexOf(".") + 1);
//console.log(fileType)
let fileType = localUri.substring(localUri.lastIndexOf(":") + 1,localUri.lastIndexOf(";")).split("/").pop();
console.log("type:", fileType)
let formData = new FormData();
formData.append("photo", {
uri : localUri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
console.log("formdata", formData)
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
let response = await fetch(`${this.props.url}imagetest`, options)
result = await response.json()
console.log(result)
My simple code for api.php in Laravel is:
Route::post("/imagetest", function (Request $request) {
return ["uploaded" => $request->hasFile("photo")];
});
Found the solution at
send image using Expo
The problem I was having, I was testing it by running the code on web, when I ran it on the device I could see the formdata as well as the image was been uploaded too

API hit using form data in ionic2

i want to hit api on form data like when I am using let params ={"supplier_id": "538","verify":"1","item_id":itemId};and api is this.aService.process('http://myapi.php', params) then it is not working .When I am trying with
let _urlParams = new URLSearchParams();
_urlParams.append('supplier_id', "538");
_urlParams.append('verify', "1");
_urlParams.append('item_id', itemId);
still it is not working and data is not showing in network . When I am using postman then if i am putting data on form-data then it is working and on raw it is not working .. What to do ?
URLSearchParams != FormData
Try sending your data with
let input = {
firstName: 'first name',
(...)
};
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('https://angular2.apispark.net/v1/contacts/', $.param(input), { headers })
.subscribe(...);

Asynchronous form-data POST request with xmlhhtprequest

I am trying to upload a file to the REST Api of Octoprint, which should be done by sending a POST request with Content-Type: multipart/form-data
(http://docs.octoprint.org/en/master/api/fileops.html#upload-file)
I am using NodeJS and two libraries, XmlHttpRequest and form-data. When trying:
var xhr = new xmlhttprequest() ;
var form = new formData() ;
form.append('exampleKey', 'exampleValue');
xhr.open("POST","octopi.local/api/local", true) ;
xhr.setRequestHeader("Content-Type","multipart/form-data") ;
xhr.send(form) ;
I get an error at the xhr.send line :
TypeError: first argument must be a string or Buffer
If I make a synchronous request by using xhr.open("POST",url,false), this error disappears.
Why is it so ? Is there a way to turn it into an asynchronous request ?
EDIT Actually, I don't really understand the documentation. I suppose that I should set the file I want to upload by using form.append("filename", filepath, "exampleName"), but I am not sure about that. The fact is that I noticed that I get the TypeError even if I try a simplified request, without sending any file.
EDIT2 This is the modified code, which returns the same error :
var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest ;
var FormData = require('form-data');
var data = new FormData();
data.append("key","value" );
var xhr = new XMLHttpRequest();
xhr.open('POST', "octopi.local/api/files/");
xhr.send(data);
After a long time working on this, I finally managed to upload a file. If you use NodeJS, don't rely on the MDN documentation: it tells what the libraries should do, not what they can actually do on the node platform. You should only focus on the docs available on GitHub.
It seems that it is not currently possible to send a form with XMLHttpRequest : I tried using JSON.stringify(form) but then wireshark tells me that the request is not a multipart/formdata request.
If you want to upload a file, you should rather use the 'request' module. The following has worked for me :
exports.unwrappeduploadToOctoprint = function(){
"use strict" ;
var form ={
file: {
value: fs.readFileSync(__dirname+'/test2.gcode'),
options: { filename: 'test2.gcode'}
}
};
var options = {
method: 'POST',
url: 'http://192.168.1.24/api/files/local',
headers: { 'x-api-key': 'E0A2518FB11B40F595FC0068192A1AB3'},
formData: form
};
var req = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
};
Seems that you have some typos in your code. Use code snippet below instead. Replace the relevant parts according to your needs
var fileToUpload = document.getElementById('input').files[0];
var data = new FormData();
data.append("myfile", fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_endpoint");
xhr.send(data);

How I can catch and save to file data from form sended by AJAX in ColdFusion

I have the followign JavaScript code:
function upload(blob) {
var xhr = new XMLHttpRequest();
var url = "test.cfm";
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("randomname",blob);
xhr.open("POST",url,true);
xhr.send(fd); }
How can I catch it on server side by ColdFusion and Save blob object to File?
Can someone please some code sample. Thx.
PS. I am pretty new in CF.
Since you are using formdata, you can access the form variable with ajax, just like you would with normal http requests.
#form.randomname#
#form['randomname']#
So you could save the content in a file with
<cfscript>
fileWrite( 'c:\myfile.txt', form.randomname );
</cfscript>

Resources