How can I save a modified image in Laravel - javascript

I'm trying to save a new photo in database which is modified, I have my javascript ( darkroomjs) for cropping photos, but the new photo doesn't save in database. I'd like to save my new photo instead of the original photo.
$profile_images = $request['profilefiles'];
$profile_images = explode(";;", $profile_images);
array_shift($profile_images);
$image = "";
foreach ($profile_images as $key => $value) {
$image_parts = explode(";base64,", $value);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$destinationPath = public_path('images/model/');
$hardPath = str_random(10) . '.' . $image_type;
$filename = $destinationPath . $hardPath;
file_put_contents($filename, $image_base64);
$image = $hardPath;
}
$model->title = $request['title'];
$model->slug = Slugify::slugify($request['title']);
$model->phone = $request['phone'];
$model->external_link = $request['external_link'];
$model->email = $request['email'];
$model->description = $request['description'];
$model->category = $request['category'];
$model->instagram = $request['instagram'];
$model->category_id = $request['category_id'];
$model->badges_id = $request['badges_id'];
$model->height = $request['height'];
$model->boost = $request['boost'];
$model->waist = $request['waist'];
$model->hips = $request['hips'];
$model->shoes = $request['shoes'];
$model->hair = $request['hair'];
$model->eyes = $request['eyes'];
$model->dress = $request['dress'];
$model->publish = $publish;
$model->age = date('Y-m-d', strtotime($request['dob']));
$model->metatitle = $request['title'];
$model->metadescription = substr(strip_tags($request['description']), 0, 160);
if ($image != "") {
var_dump($image);
$model->image = $image;
}
$model->upload_pdf = $upload_pdf;
$model->save();

Above image shows callback to get edited image.
1) You can save this file somewhere in temp folder at server by making ajax call to server.
2) During you save other fields(POST request). You can simply move file from temp folder to your images folder and file name into DB.
Ref : https://github.com/MattKetmo/darkroomjs

You can simply
$path = Storage::put('images/model', $image_base64);
This will create you a unique name and save it in your storage/app rather than public (which is what you need to do rather than saving in public/ directory itself).

Related

Combining multiple responses in dropzone js

I have a laravel 9 controller method that returns recently inserted ids. The method returns one id at a time.
public function product_images(Request $request)
{
//echo asset('storage/3fb80245e9beb3ce6cbbf68be25a0d0b.jpg');
//http://localhost:8000/storage/uploads/3fb80245e9beb3ce6cbbf68be25a0d0b.jpg
$all_ids = [];
$file = new User_files;
if ($request->file('file')) {
$filePath = $request->file('file');
$fileName = $filePath->getClientOriginalName();
$path = $request->file('file')->storeAs('uploads', $fileName, 'public');
}
$md5Name = md5_file($request->file('file')->getRealPath());
$guessExtension = $request->file('file')->guessExtension();
$file->file_name = $filePath->getClientOriginalName();
$file->file_category = 'user_files';
$file->file_path = $request->file('file')->storeAs('uploads', $md5Name.'.'.$guessExtension, 'public');
$file->user_id = auth()->user()->id;
$file->file_ai_description = 'ai desc';
$file->save();
$lid = $file->id;
array_push($all_ids,$lid);
$csv_ids = implode(', ', $all_ids);
return $csv_ids;
}
The method returns ids like
100
101
Dropzone js
success: function (file, response) {
var arr = [];
var id = JSON.parse(response);
arr.push(id);
var csv = arr.join(", ")
console.log('csv', csv);
},
is there a way i can combine individual ids returned into one comma separated list?.

Is there an easy way to update CSV with an API data?

I have a code that can get the Amazon product price if you gave it's "ASIN" (It's Amazon product identification number)... below you can find the code (I don't think there is a need to read the code anyway).
<?php
class AmazonAPI {
var $amazon_aff_id;
var $amazon_access_key;
var $amazon_secret_key;
var $url_params;
var $itemID;
var $xml;
var $operation;
var $signature;
var $response_groups = "Small,Images,OfferSummary";
var $error_message;
var $error=0;
public function __construct($affid, $access, $secret)
{
$this->amazon_aff_id = $affid;
$this->amazon_access_key = $access;
$this->amazon_secret_key = $secret;
}
public function build_url()
{
$url = "http://webservices.amazon.com/onca/xml?";
$this->response_groups = str_replace(",", "%2C", $this->response_groups);
$url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
$url_params .= "&AssociateTag=" . $this->amazon_aff_id;
if(!empty($this->itemID)) {
$url_params .= "&ItemId=" . $this->itemID;
}
$url_params .= "&Operation=" . $this->operation;
$url_params .= "&ResponseGroup=" . $this->response_groups;
$url_params .= "&Service=AWSECommerceService";
$url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
$url_params .= "&Version=2013-08-01";
$this->url_params = $url_params;
$url .= $url_params;
$url .= "&Signature=" . $this->generate_signature();
return $url;
}
public function generate_signature()
{
$this->signature = base64_encode(hash_hmac("sha256",
"GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
$this->amazon_secret_key, True));
$this->signature = str_replace("+", "%2B", $this->signature);
$this->signature = str_replace("=", "%3D", $this->signature);
return $this->signature;
}
public function item_lookup($id)
{
$this->operation = "ItemLookup";
$this->itemID = $id;
$url = $this->build_url();
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$this->xml = simplexml_load_string($output);
return $this;
}
public function check_for_errors()
{
if(isset($this->xml->Error)) {
$this->error_message = $this->xml->Error->Message;
$this->error = 1;
}
if(isset($this->xml->Items->Request->Errors)) {
$this->error_message = $this->xml->Items->Request->Errors->Error->Message;
$this->error = 1;
}
return $this->error;
}
public function get_item_price($product)
{
$price = 0;
if(isset($product->LowestNewPrice)) {
$price = $product->LowestNewPrice->Amount;
} elseif(isset($product->LowestUsedPrice)) {
$price = $product->LowestUsedPrice->Amount;
} elseif(isset($product->LowestCollectiblePrice)) {
$price = $product->LowestCollectiblePrice->Amount;
} elseif(isset($product->LowestRefurbishedPrice)) {
$price = $product->LowestRefurbishedPrice->Amount;
}
return $price;
}
public function get_item_data()
{
if($this->check_for_errors()) return null;
$product = $this->xml->Items->Item;
$item = new STDclass;
$item->detailedPageURL = $product->DetailPageURL;
$item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
$item->title = $product->ItemAttributes->Title;
$item->smallImage = $product->SmallImage->URL;
$item->mediumImage = $product->MediumImage->URL;
$item->largeImage = $product->LargeImage->URL;
$item->price = $this->get_item_price($product->OfferSummary);
return $item;
}
}
?>
Then i echo the price with this code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup("ASIN")->get_item_data();
echo $item->price;
Now if i have a csv sheet like this
https://ibb.co/dHS4EK
can i update the prices on column D and E given the asin found on column B and C,
so for example the value of cell D2 will get it using the following code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup(Value on cell D2)->get_item_data();
echo $item->price;
then save the csv file after updating it's prices, is there a simple easy way to do that in maybe php especially that i'm very new to coding?
Edit 1: I need the csv file to import it using WooCommerce import tool which only accept csv files
Thanks in advance
What you have to do is:
Parse the CSV file into an array. You can use PHP functions for that like str-getcsv
Find the correct line inside the array with either array_filter or a simple foreach loop.
Update the respective value with the new price
Create a CSV file from the array with fputcsv

how to put double variable data in ajax

i've case to use variable more the one like code bellow :
function upload(iddata,ring)
{
//variable 1
dataString ="iddata="+iddata+"&ring="+ring+""; // variable 1
//variable 2
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
// i want put both variabel in ajax like this
$.ajax({
data: {formData,dataString}, //variable 1 and 2 in group
});
}
please how source is True
You should handle your whole data as an object only, and not mix it as a string and a array in a object. In this case you would not get the expected data in your receiver.
You could change it like this:
function upload(iddata, ring) {
var data = {
iddata: iddata,
ring: ring,
formData: new FormData()
};
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
data.formData.append("file[]", file, file.name);
}
$.ajax({
data: data
});
}
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MyBird extends CI_Controller {
/**
* Index Page for this controller.
function add_bird()
{
// get user id posted
$iddata=empty($_POST['iddata']) ? '' : $_POST['iddata'];
$ring=empty($_POST['ring']) ? '' : $_POST['ring'];
//echo json_encode(array('uploaded' => 'Oke Bos'));
if ( ! empty($_FILES))
{
$config['upload_path'] = "./assets/images/uploads";
$config['allowed_types'] = 'gif|jpg|png|mp4|ogv|zip';
$this->load->library('upload');
$files = $_FILES;
$number_of_files = count($_FILES['file']['name']);
$errors = 0;
// codeigniter upload just support one file
// to upload. so we need a litte trick
for ($i = 0; $i < $number_of_files; $i++)
{
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = "Ring".$ring._.$Random_Number; //new file name
$config['file_name'] = $NewFileName;
$_FILES['file']['name'] = $files['file']['name'][$i];
$_FILES['file']['type'] = $files['file']['type'][$i];
$_FILES['file']['tmp_name'] = $files['file']['tmp_name'][$i];
$_FILES['file']['error'] = $files['file']['error'][$i];
$_FILES['file']['size'] = $files['file']['size'][$i];
// we have to initialize before upload
$this->upload->initialize($config);
if (! $this->upload->do_upload("file")) {
$errors++;
}
}
if ($errors > 0) {
echo $errors . "File(s) cannot be uploaded";
}
}
}
}
in controller i put code like bellow, but the filen can't move upload

camera photo uploaded as a File filetype with phongeap file transfer API

I'm uploading a photo taken by camera to server using file transfer API, however it's uploaded as a File filetype and the name of the photo is without the jpeg extension. The file can still be read as a image when I download, but I need to transfer the photo from the server to other API using the photo url, and the API expects to see the photo in the image filetype.
The javascript code to upload the photo:
var imgFilename = "";
//upload photo
function uploadPhoto(imageURI) {
//upload image
var fileName=imageURI.substr(imageURI.lastIndexOf('/') + 1);
//var uri = encodeURI('http://server...');
var options = new FileUploadOptions();
options.fileKey = "file";
if(fileName.indexOf('?')==-1){
options.fileName = fileName;
}else{
options.fileName = fileName.substr(0,fileName.indexOf('?'));
}
options.mimeType = "image/jpeg";//文件格式,默认为image/jpeg
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
options.headers = {Connection: "close"};
var ft = new FileTransfer();
ft.upload(imageURI, serverURL() + "/upload.php", win, fail, options);
}
function win(r){
if (imgFilename != ""){
deleteOldImg(imgFilename);
}
var arr = JSON.parse(r.response);
imgFilename = arr[0].result;
alert(r.response);
}
PHP code:
<?php
try{
$filename = tempnam('images', '');
$new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
unlink($filename);
//print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "image/user-photo/2/" . $new_image_name);
$json_out = "[" . json_encode(array("result"=>$new_image_name)) . "]";
echo $json_out;
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
The error code happens when PHP code is move_uploaded_file($_FILES["file"]["tmp_name"], 'image/user-photo/2/');

PHP Image Upload Not Resizing When Sent Via JS

I am running into issues when uploading an image sent to PHP via JS. I can upload the image fine, but I would to resize the image before moving it to it's new destination. I can also rename the image without any issues. It's really just the resizing that is the issue here.
After a lot of searching I have seen a lot of questions regarding this on SO, which is how I got to where I am now, but not one that answers this 100%. If you know of a question/answer already on SO please link me to the correct article.
Any help is much appreciated, thanks.
Here is the JS
var test = document.querySelector('#afile');
test.addEventListener('change', function() {
var file = this.files[0];
var fd = new FormData();
fd.append('afile', file);
// These extra params aren't necessary but show that you can include other data.
fd.append('id', burgerId);
var xhr = new XMLHttpRequest();
// why wont this work in the actions directory?
xhr.open('POST', 'actions/upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var uploadProcess = document.getElementById('uploadProcess');
uploadProcess.setAttribute('style', 'width: ' + percentComplete + '%;');
// uploadProcess.innerHTML = parseInt(percentComplete) + '% uploaded';
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
image = 'img/' + resp.newFileName;
sessionStorage.setItem('burgerLoc', image);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
// upImage(id)
}, false);
Here is the markup
<input type="file" name="afile" id="afile" accept="image/*"/>
Here is the PHP
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($image_tmp);
} else if($ext == 'png') {
$src = imagecreatefrompng($image_tmp);
} else {
$src = imagecreatefromgif($image_tmp);
}
$file_content = file_get_contents($image_tmp);
$data_url = 'data:' . $image_type . ';base64,' . base64_encode($file_content);
list($width,$height) = getimagesize($image_tmp);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
// rename the file
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = '../img/' . $new_file_name;
imagejpeg($img_dest,$new_file_name,100);
move_uploaded_file($image_tmp, $new_file_location);
imagedestroy($src);
imagedestroy($img_dest);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
I would maybe try installing ImageMagick in your linux distribution and try to use this function to resize the image
http://php.net/manual/en/imagick.resizeimage.php
I have reproduced your script on my webserver... I have made modifications and came up with this.
The most significant modification is that I am using exact paths in the file locations, and that I am moving the tmp file to a real file, load that real file, resize that real file instead of trying it to do with the tmp uploaded file.
PHP:
<?php
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
$outputfolder = "/var/www/html/wp-content/";
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = $outputfolder.$new_file_name;
move_uploaded_file($image_tmp, $new_file_location);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($new_file_location);
} else if($ext == 'png') {
$src = imagecreatefrompng($new_file_location);
} else {
$src = imagecreatefromgif($new_file_location);
}
list($width,$height) = getimagesize($new_file_location);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
$resizedLocation = $outputfolder."resized_".$new_file_name;
imagejpeg($img_dest,$resizedLocation,100);
imagedestroy($src);
imagedestroy($img_dest);
$file_content = file_get_contents($resizedLocation);
$data_url = 'data:image/jpeg;base64,' . base64_encode($file_content);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
?>
Your HTML/JS stays untouched.
Now this works for me flawlessly, the only thing you have to make sure
the $outputfolder is writeable by the linux user under which the webeserver executing the php script is runnging (typically web-data...)
My web server:
CentOS Linux release 7.0.1406 (Core)
php.x86_64 5.4.16-23.el7_0.3
apache x86_64 2.4.6

Categories