image uploaded by android is empty to laravel - android

Android is uploading image from my laravel 5.7 API but the
$request->input('image') is always on empty. I also try it using postman and its working fine. can someone help me out? XD
success result using post man form-data type
if($request->hasFile('image'))
{
$image = $request->file('image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('uploads/messenger');
$image->move($destinationPath, $name);
$path = url('')."/webservices/public/uploads/messenger/".$name;
$result=[
"image_url" => $path,
];
$succes = "1";
$successMessage = "Image uploaded";
$errorMessage = "";
}
else
{
$result = (object) array();
$succes = "0";
$successMessage = "";
$errorMessage = "Image not found";
}

use Storage Facades for storing file :
create folder inside storage/app/public/uploads/messenger : with 777 permission
run command : php artisan storage:link to symlink your storage folder content available to public folder
in your controller :
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
public function upload_image(Request $request){
try{
// added validator for image field
$validator = Validator::make($request->all(), [
'image'=>'required|mimes:jpeg,jpg,png,gif|max:5120'
]);
if ($validator->fails()) {
$response=array('status'=>'error','result'=>0,'errors'=>implode(',',$validator->errors()->all()));
return response()->json($response, 200);
}else{
if($request->hasFile('image')){
$uniqueid=uniqid();
$original_name=$request->file('image')->getClientOriginalName();
$size=$request->file('image')->getSize();
$extension=$request->file('image')->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$imagepath=url('/storage/uploads/messenger/'.$filename);
$path=$request->file('image')->storeAs('public/uploads/messenger/',$filename);
$response=array('status'=>'success','result'=>1,'image'=>$imagepath);
return response()->json($response, 200);
}else{
$response=array('status'=>'error','result'=>0,'errors'=>'no image found');
return response()->json($response, 200);
}
}
}catch(\Exception $e){
$response=array('status'=>'error','result'=>0,'errors'=>'Internal Server Error');
return response()->json($response, 500);
}
}
add Content-Type : multipart/form-data header when uploding image from client side like android or postman

Related

Image not saving in public folder

I have an API, which I have created with Laravel, which accepts images from an Android device, I want to store the image received in public/img folder, but when I check the public\img folder the image isn't there, please what may be the issue, the image location even saves successfully in the db
public function SellPost(Request $request){
$user = User::where('id', $request->user_id)->first();
$goods = new Goods;
$goods->name = $request->name;
if($request->description){
$goods->description = $request->description;
}
$goods->category_id = $request->cat_id;
$goods->amount = $request->amount;
$goods->quantity = $request->qty;
$goods->seller_id = $request->user_id;
if($goods->save()){
if($request->hasFile('photo')){
$path = Storage::disk('public')->putFile('img', $request->file('photo'));
$filename = basename($path);
// Image::make($images->uri)->save(public_path('img/' . $filename));
$saver = new Images;
$saver->product_id = $goods->id;
$saver->location_url = 'img/'.$filename;
$saver->save();
// $this->imagesUpload($goods->id, $request->photo);
}else{
return response()->json(['error'=>'Internal Server Error, Please try again Later'], 401);
}
};
return response()->json(['success'=>'Goods Posted Successfully'], $this->successStatus);
}
I got 2 solutions for you
1 : In config/filesystems.php, you could do this... change the root element in public
'disks' => [
'public' => [
'driver' => 'local',
'root' => public_path() . '/uploads',
'url' => env('APP_URL').'/public',
'visibility' => 'public',
]
]
and you can access it by
Storage::disk('public')->put('filename', $file_content);
2: you can put the file path and try to save it.
$file = $request->hasFile('photo');
$file->store('toPath', ['disk' => 'public']);
goodluck
You can try replacing
$path = Storage::disk('public')->putFile('img', $request->file('photo'));
with
$path = Storage::disk('public')->putFile( public_path('img'), $request->file('photo'));
Had this issue at some point and that was how I resolved it.

Rest api return list of images with Node JS to Android user

Good evening,
I seek how to retrieve the result of a c ++ file (main.cpp) then I send it to an android user, I'm talking about JSON (REST).
that is to say, after storing the image on the server (sent by the user) I have to run the main.cpp file and I get the result (of the image sets) and then I send it to user (android application).
so I tried to store the image on my server through this code (works):
pp.post('/up', function(req, res) {
var pathimg;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
pathimg = fs.createWriteStream('/home/usr1/Public/server/files/' + filename);
file.pipe(pathimg);
fs.readFile('/home/usr1/Public/server/files/'' + filename, unction read(err, data)
{
if(err){
res.json({'response':"Error upload"});
}else
{
res.json({'response':"Saved to server :)"});
}
});
};
I tried running the main.cpp and recovers its result:
var exec = require('child_process').exec;
var cmd = './test';
exec(cmd, function(error, stdout, stderr) {
// La résultat est dans stdout
console.log('stdout ->>: '+stdout);
console.log('stderr: '+stderr);
if(error !== null){
console.log('Ops Problem of exec : ' +error);
}
});
but this code executes the file without retrieving the results in a JSON object

Titanium Alloy Android Login

I am having an issue with a Titanium App, the issue is only with Android, iOS is fine.
So I have a login form that queries the database, pretty straightforward. But for some reason it is not passing the params to the login script.
My JS function in app, have set the alert on the else statement to print out the $.email.value and password values which read fine. But with the current $response which is just a json it shows the values as being blank? The php form is also below. As I have said this is working fine on iOS
function login(e) {
//function to use HTTP to connect to a web server and transfer the data.
var sendit = Ti.Network.createHTTPClient({
onerror : function(e) {
Ti.API.debug(e.error);
alert('There was an error during the connection');
},
timeout : 100000,
});
//Here you have to change it for your local ip
sendit.open('GET', 'http://soyo.taylorhoganit.co.uk/post_auth.php');
var params = {
email : $.email.value,
password : $.password.value,
};
sendit.send(params);
//Function to be called upon a successful response
sendit.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true)
{
var landing = Alloy.createController("landing").getView();
$.index.close();
landing.open();
// Ti.App.Properties.setString('email', $.email.value);
// Ti.App.Properties.setString('password', $.password.value);
//alert("Username: " + response.username);
}
else
{
alert($response);
}
};
};
PHP Script
<?php
// Connect to the database(host, username, password)
$con = mysql_connect('replaced values');
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db('soyo');
if (!$db)
{
echo "Failed to select db.";
exit;
}
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email = '" . $email . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$response = array(
'logged' => true,
'email' => $row['email']
);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
'logged' => false,
'message' => $email + $password
);
echo json_encode($response);
}
?>
You did a mistake by using $response in the alert. It is a PHP variable not JS.
var response = JSON.parse(json);
// ...
alert($response); // Here should be just `response`
Edit: The another problem is that you are sending GET request while in PHP you accept POST ,so you can't get any params...
There is a mistake when you want to show alert.
You are using now is alert($response);
Remove $ from $response and use alert(response);, it will work properly.

jsPDF with Cordova - Adding images

I am trying to generate a PDF using the jsPDF library (https://github.com/MrRio/jsPDF) from within a mobile Cordova app. I am currently testing the app on an Android 4.0.4 device but it also needs to run on Windows mobile 8. The text in the PDF document is shown correctly however any images are scrambled. See image below
I did find this page (https://coderwall.com/p/nc8hia) that seemed to indicate there is a problem with jsPDF displaying images in Cordova (see comments) but the author never posted the follow-up. Has anyone been able to use jsPDF with Cordova and properly add images to the generated PDF? My code is below, any assistance or advice would be greatly appreciated.
function demoReceipt() {
var img = new Image();
img.onError = function() {
alert('Cannot load image: "' + url + '"');
};
img.onload = function() {
createPdf2(img);
};
img.src = 'img/testlogo.png';
}
function createPdf2(myLogo) {
// var doc = new jsPDF('p', 'pt', 'jontype');
var doc = new jsPDF('p', 'pt', 'letter');
doc.setProperties({
title : 'Fueling Receipt',
author : 'Jon Hoffman',
creater : 'Jon Hoffman'
});
doc.addImage(myLogo, 'PNG', 5, 5, 140, 30);
doc.setFontSize(12);
doc.text(10, 40, 'Sample PDF receipt');
doc.setFontSize(8);
doc.text(10, 45, 'Smaller text - new');
var pdfOutput = doc.output();
//NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
//Requires cordova plugin add org.apache.cordova.file
console.log("file system...");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
console.log(fileSystem.root.fullPath);
fileSystem.root.getDirectory("myPDFs", {
create : true,
exclusive : false
}, function(dir) {
fileSystem.root.getFile("myPDFs/test.pdf", {
create : true
}, function(entry) {
var fileEntry = entry;
console.log(entry);
entry.createWriter(function(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
console.log("writing to file");
writer.write(pdfOutput);
}, function(error) {
console.log(error);
});
}, function(error) {
console.log(error);
});
}, function(error) {
});
}, function(event) {
console.log(evt.target.error.code);
});
}
I solved the issue with help from this blog post: https://coderwall.com/p/nc8hia. There does seems to be significant differences between the 0.90 version used in that post and the version that I am using from https://github.com/MrRio/jsPDF however the solution is pretty much the same.
First off, in the version from MyRio, you can get the PDF generation working without fixing the Blob issue noted in Igor’s post. All you need is to generate the PDF output by calling “doc.ouput()” and then save it using the Cordova filesystem plugin. So I thought I did not have to create the Blob (this is where I was wrong).
Igor (from the coderwall post) responded back to my question with some additional code but when I searched the jspdf.js file from MyRio version, I saw that the code (more compact version) was already in the code on lines 734 – 738:
var data = buildDocument(), len = data.length,
ab = new ArrayBuffer(len), u8 = new Uint8Array(ab);
while(len--) u8[len] = data.charCodeAt(len);
return new Blob([ab], { type : "application/pdf" });
But I also notice that the blob creation code that Igor fixed in his initial post was at the end of this block of code. So I commented out the “return new Blob([ab], { type : “application/pdf”});” line and put in the following code from Igor’s post with minor variable name changes:
try
{
var blob = new Blob([ab], {type: "application/pdf"});
console.debug("case 1");
return blob;
}
catch (e)
{
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if (e.name == 'TypeError' && window.BlobBuilder)
{
var bb = new BlobBuilder();
bb.append(ab);
console.debug("case 2");
return bb.getBlob("application/pdf");
}
else if (e.name == "InvalidStateError")
{
// InvalidStateError (tested on FF13 WinXP)
console.debug("case 3");
return new Blob([ab], {type: "application/pdf"});
}
else
{
// We're screwed, blob constructor unsupported entirely
console.debug("Errore");
}
}
Then when I generate that pdfOutput, in my code, I changed
var pdfOutput = doc.output();
to
var pdfOutput = doc.output(“blob”);
and it worked.
I hope this post is able to help out others experiencing the same issues.

How to move captured image in PhoneGap to a folder in sdcard

I am using following code to get image base64 data to display and upload to server.
But i want to save this captured image in sdcard folder. Please help me to do this.
This is necessary for me to get base64 image data because server support only this format. That's why i am using destinationType = 0 (means DATA_URL). I have base64 image data now but how can i save this data to sdcard?
uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail);
function uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail)
{
pictureSource = navigator.camera.PictureSourceType;
if (isSourceCamera)
{
//QUALITY MUST BE LOW TO AVOID MEMORY ISSUES ON IPHONE4 ! (and other low memory phones).
//must resize to make it faster to upload and avoid failure with low memory phones.
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.CAMERA,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
else
{
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.PHOTOLIBRARY,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
}
function onPhotoDataSuccess(imageData)
{
**//I want to smae my image here in sdcard folder.**
var nodeid = localStorage.getItem("user_nodeid");
var modifyImgData = imageData.replace(' ', '+');
document.getElementById('image').src = setLocalStorageImage(localStorage.getItem(nodeid+"image"), modifyImgData);
document.getElementById('profileMenu').src = setLocalStorageImage(localStorage.getItem(nodeid+"smallimage"), modifyImgData);
$.ajax({
type: "POST",
url: appURL+"api/upload/image/" +nodeid+ "/1",
data: "image=" + encodeURIComponent(modifyImgData),
success: function(msg){
//No need to do anything here
if (msg.documentElement.getElementsByTagName("message")[0].childNodes[0].nodeValue != 'success')
onFail('Error in uploading image at server. Please try again.');
}
});
}
function onFail(message){
alert(message);
}
Here is the correct answer to the original question:
How to move captured image in PhoneGap to a folder in sdcard?
function onfail(error,caller){
error = error || '[error]';
caller = caller || '[caller]';
alert('Error > '+caller+" code: "+error.code);
};
/*
Error codes
NOT_FOUND_ERR = 1;
SECURITY_ERR = 2;
ABORT_ERR = 3;
NOT_READABLE_ERR = 4;
ENCODING_ERR = 5;
NO_MODIFICATION_ALLOWED_ERR = 6;
INVALID_STATE_ERR = 7;
SYNTAX_ERR = 8;
INVALID_MODIFICATION_ERR = 9;
QUOTA_EXCEEDED_ERR = 10;
TYPE_MISMATCH_ERR = 11;
PATH_EXISTS_ERR = 12;
*/
function doCameraAPI() {
// Retrieve image file location from specified source
navigator.camera.getPicture(getImageURI, function(message) {
alert('Image Capture Failed');
}, {
quality : 40,
destinationType : Camera.DestinationType.FILE_URI
});
}; //doCameraAPI
function getImageURI(imageURI) {
//resolve file system for image to move.
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, function(error){onfail(error,'Get Target Image')});
function gotFileEntry(targetImg) {
//alert("got image file entry: " + targetImg.name);
//now lets resolve the location of the destination folder
window.resolveLocalFileSystemURI(POSTPATH, gotDestinationEntry, function(error){onfail(error,'Get Destination Dir')});
function gotDestinationEntry(destination){
// move the file
targetImg.moveTo(destination, targetImg.name, moveSuccess, function(error){onfail(error,'Move Image')});
alert('dest :'+destination.fullPath);
};
function moveSuccess(){
alert('FILE MOVE SUCCESSFUL!');
};
}; //getImageURI
credit to: nbk on the google phonegap group.
Since you have the data in Base64 format you can just use the FileWriter to save the data to disk.
I think you need to capture the image as FILE_URL, and save the image to sdcard first as mentioned by Steven Benjamin above.
Then you can retrive the base64 DATA_URL as
function readFile() { // button onclick function
var gotFileEntry = function(fileEntry) {
console.log("got image file entry: " + fileEntry.fullPath);
fileEntry.file( function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read complete!");
image64.value = evt.target.result;
};
reader.readAsDataURL(file);
}, failFile);
};
window.resolveLocalFileSystemURI("file:///mnt/sdcard/test.jpg", gotFileEntryImage, function(){console.log("* * * onPhotoURISuccess" + failed);});
}

Categories

Resources