How to get parameter of ng2-file-upload with endback? - php

I want to get parameter with php. I try with my code but it still not work save into folder (parameter) this is post http image:
Ionic framework
this.uploader.onBeforeUploadItem = (item: any) => {
this..uploader.options.additionalParameter = {
folder : this.herb_id <---- my parameter folder name
};
endback(php)
<?php
header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'POST');
header('Access-Control-Allow-Headers', 'Content-Type, Content-Range, Content-Disposition, Content-Description,X-Requested-With');
header('Access-Control-Allow-Credentials', true);
if (isset($_FILES['file'])) {
/------------- folder name --------------------------//
$path = 'uploads/';
$path .=$_FILES['options']['additionalParameter']['folder']; <---- folder name
$path .= '/';
$originalName = $_FILES['file']['name'];
$ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION);
$generatedName = md5($_FILES['file']['tmp_name']).$ext;
//$filePath = $path.$generatedName;
$filePath = $path.$generatedName;
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}

i can solve it as this code
for ionic
this.fileField.uploader.onBuildItemForm = (fileItem, form) => {
form.append('folder', String(this.herb_id));
return { fileItem, form };
};
for php
/------------- folder name --------------------------//
$path = 'uploads/';
$path .=$_POST['folder']; <---- folder name
$path .= '/';

Related

[PHP][SLIM] move_uploaded_file never ends with larger files in Hosting24

I have a question.
I'm trying to upload files to a server, this server is hosted by 'Hosting24', i don't know if that matters, anyway, if I try to move files larger than 70mb It never ends to load and never send a response, my server config is okay, it has these values: {"post_max_size":"512M","memory_limit":"1024M"}
I has tryed with $_FILES and ftp transfer and it doesnt works, it never ends of load.
I'm using Slim framework and this is the function:
public function testCode($request, $response, $args)
{
$data = $request->getParsedBody();
$uploadedFiles = $request->getUploadedFiles();
//here take files
$uploadedFile = $uploadedFiles['file_user'];
$nameC = $data['nombre_curso'];
//here set path
$path = "../../scorm/temp/" . $nameC . '/';
//Creating folders
if (!#mkdir($path, 0777, true)) {
$error = error_get_last();
echo $error['message'];
}
$file_name = $uploadedFile->getClientFilename();
$array = explode(".", $file_name);
$ext = $array[1];
//if is a zip file
if ($ext == 'zip') {
$location = $path . "/" . $file_name;
//here move the uploaded file to my selected directory
if (move_uploaded_file($uploadedFile->file, $location)) {
$obj = (object) array("response" => 'works', 'post_max_size' => ini_get('post_max_size'), 'memory_limit' => ini_get('memory_limit'));
$response->withStatus(200);
$response->getBody()->write(json_encode($obj));
return $response;
} else {
$error = error_get_last();
echo $error['message'] . " it couldn't be moved";
}
} else {
echo "no zip";
}
}

How to upload a image using Slim Framework

I want to storage a image in server and save the path in MySQL, but i'm not finding a good code to do it.
I found this, but does not work:
$container = $app->getContainer();
$container['upload_directory'] = __DIR__ . '../uploads';
$app->post('/photo', function (Request $request, Response $response) use ($app) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['picture'];
if($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->write('uploaded ' . $filename . '<br/>');
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(),
PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
Somebody knows how to upload image and save the path in MySQL?
First you need a database connection for MySQL. Read more
Then create a table, e.g. files(id, path, filename)
To insert the record (after the upload) into the table, you could use an SQL statement as follows:
// ...
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('File uploaded: ' . $filename);
$row = [
'path' => $directory,
'filename' => $filename
];
$sql = "INSERT INTO files SET path=:path, filename=:filename;";
$pdo->prepare($sql)->execute($row);
// ...
return $response;
Please note that $response->write('...') will not work. It must be $response->getBody()->write('my content');.
Edit: Make sure that the uploads/ directory exists and the directory has write access. For example chmod -R 1777 uploads/

How to rename an uploaded file so that it is unique?

I have an upload form on a site that uploads multiple files to a server, and also sends me an email.
It is written in php, with the main file part being the following:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
// Define allowed extensions
// blahblahblah checking
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
Nowadays, people upload pictures from a cell phone and often they are all named the same file name: image.jpg (or something similar) - so they get overwritten.
I would like to append a counter on to each multiple file (like 1,2,3...) name so they are uploaded and sent with unique names, even though the client sends them as same name.
Something like:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
// Define allowed extensions
// counter= counter++;
// newFilename=oldFileName+String(counter);
// doRestStuffNewFileName();
// blahblahblah checking
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];`
`move_uploaded_file($temp_name, $server_file);`
array_push($files, $server_file);`
How can I modify it as such in php?
ok new comments:
I would like:
for int i=0;i<files[attached];i++;
fileName=files[i]
newFileName=filename+String(Integer(i));
uploadWithNewFileName();
writeToServerWithNewFileName();
This is php current code:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
foreach ($_FILES as $name => $file) {
if (!$file['name'] == "") {
$file_name = $file['name'];
$size += $file['size'];
$temp_name = $file['tmp_name'];
$path_part = pathinfo($file_name);
$ext = $path_part['extension'];
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
}
}
Why doesnt this work:
if (isset($_FILES) && (bool) $_FILES) {
$files = array();
$ext_error = "";
counter =0; //My code
foreach ($_FILES as $name => $file) {
counter++; //My code
if (!$file['name'] == "") {
$file_name = $file['name'];
$size += $file['size'];
$temp_name = $file['tmp_name'];
$path_part = pathinfo($file_name) + counter; //My code
$ext = $path_part['extension'];
// Store attached files in uploads folder
$server_file = dirname(__FILE__) . "/uploads/" . $path_part['basename'];
move_uploaded_file($temp_name, $server_file);
array_push($files, $server_file);
}
}

Laravel: Save Base64 .png file to public folder from controller

I send a png image file to controller in base64 via Ajax. I've already test and sure that controller has received id but still can't save it to public folder.
Here is my controller
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
$png_url = "product-".time().".png";
$path = public_path('img/designs/' . $png_url);
Image::make($image->getRealPath())->save($path);
// I've tried using
// $result = file_put_contents($path, $image);
// too but still not working
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
Intervention Image gets binary data using file_get_content function:
Reference : Image::make
Your controller should be look like this:
public function postTest() {
$data = Input::all();
$png_url = "product-".time().".png";
$path = public_path().'img/designs/' . $png_url;
Image::make(file_get_contents($data->base64_image))->save($path);
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
$data = Input::all();
$png_url = "perfil-".time().".jpg";
$path = public_path() . "/img/designs/" . $png_url;
$img = $data['fileo'];
$img = substr($img, strpos($img, ",")+1);
$data = base64_decode($img);
$success = file_put_contents($path, $data);
print $success ? $png_url : 'Unable to save the file.';
$file = base64_decode($request['image']);
$safeName = str_random(10).'.'.'png';
$success = file_put_contents(public_path().'/uploads/'.$safeName, $file);
print $success;
This is an easy mistake.
You are using public_path incorrectly. It should be:
$path = public_path() . "/img/designs/" . $png_url;
Also, I would avoid your method of sending the image. Look at a proper upload in a form and use Laravel's Input::file method.
My solution is:
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
Storage::disk('local')->put('imgage.png', $image);
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
echo $storagePath.'imgage.png';
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
what am i doing is using basic way
$file = base64_decode($request['profile_pic']);
$folderName = '/uploads/users/';
$safeName = str_random(10).'.'.'png';
$destinationPath = public_path() . $folderName;
file_put_contents(public_path().'/uploads/users/'.$safeName, $file);
//save new file path into db
$userObj->profile_pic = $safeName;
}
Store or save base64 images in the public folder image and return file path.
$folderPath = public_path() . '/' . 'images/';
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$uniqid = uniqid();
$file = $folderPath . $uniqid . '.' . $image_type;
file_put_contents($file, $image_base64);
return $file;
Actually, Input::all() returns an array of inputs so you have following:
$data = Input::all();
Now your $data is an array not an object so you are trying to access the image as an object like:
$data->base64_image
So, it's not working. You should try using:
$image = $data['base64_image'];
Since it's (base64_image) accessible from $_POST then Input::file('base64_image') won't work because Input::file('base64_image') checks the $_FILES array and it's not there in your case.
Here is my solution for the file upload from base_64.
public static function uploadBase64File(Request $request, $requestName = 'imageData', $fileName = null, $uploadPath = 'uploads/images/')
{
try {
$requestFileData = $request->$requestName;
// decode the base64 file
$file = base64_decode(preg_replace(
'#^data:([^;]+);base64,#',
'',
$request->input($requestName)
));
if (in_array($file, ["", null, ' '])) {
return null;
}
//handle base64 encoded images here
if ($fileName == null) {
$fileName = Str::random(10);
}
$extension = '.' . explode('/', explode(':', substr($requestFileData, 0, strpos($requestFileData, ';')))[1])[1];
$filePath = $uploadPath . '' . $fileName . '' . $extension;
// dd($extension);
if (!File::exists(public_path($uploadPath))) {
File::makeDirectory(public_path($uploadPath), 0777, true);
}
// dd($filePath);
$ifImageUploadSuccessful = File::put(public_path($filePath), $file);
if (!$ifImageUploadSuccessful) {
return null;
}
return '/' . $filePath;
// throw new Exception("Unable To upload Image");
} catch (Exception $e) {
// dd($e);
throw new Exception($e->getMessage());
}
}
I'v done it!!
I replaced
$data->base64_image to $_POST['base64_image'] and then use
$result = file_put_contents($path, $image);
instead of Image::make($image->getRealPath())->save($path);
But this doesn't look like a laravel ways. I you have another way that look more elegant please tell me!

move uploaded file success but could not find file in folder

I have the following code
public function upload() {
if($_FILES){
$this->load->model('account/customer');
$file = $_FILES['profile'];
$file_name = $file['name'];
// $ext = end(explode('.', $file_name));
// $file_name = 'na_'.md5(time()).'.'.$ext;
echo $file_content = $file['tmp_name'];
$data = array('customer_id' => $this->customer->getId(), 'img_url' => $file['name']);
$this->model_account_customer->profileImage($data);
echo 'test/'.$file_name;
$img = move_uploaded_file($file['tmp_name'], 'test/'.$file['name']);
if($img) {
$return = json_encode(array('status' => 1));
} else {
$return = json_encode(array('status' => 0));
}
echo $return;
}
}
The above code returning status as 1 but could not see the file in folder.
I check folder permission is 0777
Try appending a / in front of the path
move_uploaded_file($file['tmp_name'], '/test/'.$file['name']);

Categories