I am new In Reactjs and php, I have index.js (page in Reactjs/nextjs) and i am sending image data (using multipart form data) And in Php i am trying to upload image but whenever i am trying to upload image then uploaded image showing error "we dont support this format", So please tell me how can i simply upload image using "file_get_contents" method, Here is my code in php (which is uploading incorrect image or 0 byte image), i tried with 2 ways , First way/code is
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode(explode( ',', $files)[1]);
$file_name =$_FILES['file']['name'];
$file_ext = strtolower( end(explode('.',$file_name)));
define('UPLOAD_DIR', 'uploads/');
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$file_name = UPLOAD_DIR . uniqid() . time() . '.' . $file_ext;
move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
Second way is
$file_name =$_FILES['file']['name'];
$file_ext = strtolower( end(explode('.',$file_name)));
define('UPLOAD_DIR', 'uploads/');
$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]);
$file = UPLOAD_DIR . uniqid() . '.'.$file_ext;
file_put_contents($file, $image_base64);
I have a simple upload class that I edit for each project, test it, hope it helps
class Upload
{
//300 kb
private static $MAX_FILE_SIZE = 300 * 1024;
private static $ALLOWED_FILE_TYPES = ['png', 'jpg', 'jpeg'];
private static $key;
private static $ImageFileType;
public static function uploadTeamLogo($key, $short_name, $relativePath)
{
self::$key = $key;
if (!self::isImage())
apiErrorMessage("Not an image!");
if (!self::fileTypeIsAllowed(basename($_FILES[self::$key]["name"])))
apiErrorMessage("Only png, jpg, jpeg Images are allowed!");
if (self::isSizeTooLarge())
apiErrorMessage("Max file size is 300kb!");
$image_name = $short_name . "_" . generateHash(12) . "." . self::$ImageFileType;
$target_dir = getcwd() . $relativePath . $image_name;
if (self::doUpload($target_dir))
return $image_name;
else
return false;
}
private static function isImage()
{
return getimagesize($_FILES[self::$key]["tmp_name"]) == true;
}
private static function alreadyExist($target_file)
{
return file_exists($target_file) === true;
}
private static function isSizeTooLarge()
{
return $_FILES[self::$key]["size"] > self::$MAX_FILE_SIZE === true;
}
private static function fileTypeIsAllowed($target_file)
{
self::$ImageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
foreach (self::$ALLOWED_FILE_TYPES as $type)
if (self::$ImageFileType == $type)
return true;
return false;
}
private static function doUpload($target_file)
{
return move_uploaded_file($_FILES[self::$key]["tmp_name"], $target_file) == true;
}
}
use like this:
$image_name = Upload::uploadTeamLogo($key, $short_name, $path);
Related
I am trying to upload image in laravel but i am getting error when I am uploading image in folder, When I am uploading image and clicking on submit button, it's giving me problem in uploading file, i think there are error in this line...
move_uploaded_file($imageName, $moveable_file);
here are my usercontrolle.php file
public function dropzone(Request $request)
{
$user = Auth::user()->toArray();
$user_id = $user['id'];
$type = 'photo';
$type_id=0;
$data = $_FILES["image"];
//dd($data);
$doc_id = $_POST["doc_id"];
$doc_name = $_POST["doc_name"];
if($doc_id)
{ $img_id=$doc_id;
$img_name=$doc_name;
$response = $this->userService->deleteDocument($img_id,$img_name,$user_id,$type,$type_id);
}
// $image_array_1 = explode(";", $data);
// $image_array_2 = explode(",", $image_array_1[1]);
// $data = base64_decode($image_array_2[1]);
$storage_path = env('DOCUMENT_STORAGE_PATH');
$profile_upload_dir = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $storage_path);
if($type_id != '0'){
$destination_path = $profile_upload_dir . $user_id ."\\". $type."\\". $type_id;
$destination_path = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path);
}else{
$destination_path = $profile_upload_dir . $user_id ."\\". $type;
$destination_path = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path);
}
if(!is_dir($destination_path)) {
mkdir($destination_path, 0777,true);
}
$imageName = time() . '.png';
// dd($imageName);
$moveable_file = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path.'\\'.$imageName);
//dd($moveable_file);
move_uploaded_file($imageName, $moveable_file);
// file_put_contents($moveable_file, $data);
//$image_file = addslashes(file_get_contents($moveable_file));
$user = Auth::user()->toArray();
//dd($user);
$user_id = $user['id'];
$type_id = 0;
if(isset($photo['type_id']) && !empty($photo['type_id'])){
$type_id = $photo['type_id'];
}
//$photo['file']=$_FILES['photoimg'];
$photo['type']='photo';
$result = $this->userService->storeUserDocuments($imageName, $photo['type'], $type_id, $user_id);
// echo '<img src="data:image/png;base64,'.base64_encode($data).'" data-action="zoom" class="pull-left" style="height: 130px;width:130px;">';
}
You can also use image intervention to upload images.
First, install this on your laravel project using
composer require intervention/image
After installation open config/app.php and then add these in the $providers array.
Intervention\Image\ImageServiceProvider::class
Also, add the facade of this package to the $aliases array.
'Image' => Intervention\Image\Facades\Image::class
After this, you are ready to add images
Add this to your controller
use Intervention\Image\Facades\Image;
Here is a sample example of how to add images, use this in the controller
//Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension(); //use time to create file name
Image::make($avatar)->resize(300,300)->save( public_path('/images/'.$filename) );
$user->avatar = $filename;
//Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('/images/'.$filename) );
$user->avatar = $filename;
// $user->save(); //To save the name of the file in the database
}
}
<?php
include 'model.php';
$rs=new database();
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$res=$rs->insert($emapData[0],$emapData[1],$emapData[2],$emapData[3],$emapData[4],$emapData[5]);
$result=mysql_fetch_array($res);
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"result.php?msg=valid\"
</script>";
}
}
fclose($file);
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"result.php?msg=valid\"
</script>";
mysql_close($conn);
}
}
?>
this code only uploads csv file but i want to upload xls too with this code. if possible i want to upload all format of excel . and the rest of code is working fine and also i dont want to change the method.
Download PHPExcel
https://github.com/PHPOffice/PHPExcel
and create this function
function getDataFromExcel($filename)
{
$excel = PHPExcel_IOFactory::load($filename);
$sheet = $excel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$sheetData = $sheet->toArray(null, true, true, true);
return $sheetData;
}
It will return data in array
if you want to know the type of file use this method
function getFileType($key)
{
//Define type
$type = 'unknow';
if(isset($_FILES[$key])) {
$file = $_FILES[$key];
$fileType = $file['type'];
if (strrpos($fileType, 'csv')) {
$type = 'csv';
} else if (($fileType == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || ($fileType == 'application/vnd.ms-excel')) {
$type = 'excel';
}
}
return $type;
}
I am using this upload widget in my web application.
I am using the FormDataUploader and I am able to upload files to a server directory quite well. However, I wanted to send extra parameters as well to the php file handling the upload. This is what I attempted:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploader : 'Ext.ux.upload.uploader.FormDataUploader',
uploaderOptions : {
url : 'uploadGallery.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
As you can see, I used the uploadParams, however, my PHP couldn't seem to receive it. In my php file, I have:
$ID_Person = $_GET['ID_Person'];
$ID_CI = $_GET['ID_CI'];
However, my PHP seems to be unable to get these params.
What I did next was to use the default ExtJS Uploader as such:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
At first, I used the old PHP file which was able to get the extra params I sent. However, it seems that I needed to use a different PHP file for the ExtJS uploader.
This is what my PHP file looks like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
require __DIR__ . '_common.php';
$config = require __DIR__ . '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
// $outputFilename = $config['upload_dir'] . '/' . $fileName;
$outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response();
However, I am getting an Internal Server 500 Error - Meaning that there was something probably wrong with my php file.
I mainly have two questions:
How do I make the uploadParams work with the FormDataUploader?
How do I write a PHP uploader for an ExtJS Data Uploader?
Got it to work.
The uploadExtJS.php file should look like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
// require __DIR__ . '_common.php';
// $config = require __DIR__ . '_config.php';
require_once '_common.php';
$config = require_once '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
$outputFilename = $config['upload_dir'] . '/' . $fileName;
// $outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response(true, "okay");
_common.php looks like:
<?php
function _log($value){
error_log(print_r($value, true));
}
function _response($success = true, $message = 'OK'){
$response = array(
'success' => $success,
'message' => $message
);
echo json_encode($response);
exit();
}
function _error($message){
return _response(false, $message);
}
_config.php should look like:
<?php
return array(
'upload_dir' => 'gallery',
'fake' => false
);
?>
and now I'm working on using a unique name using uniqid() and microtime(), as well as saving the images to a subdirectory (or any folder under your main upload/gallery folder) using the uploadParams() property.
EDIT 1: RENAMING THE UPLOADED FILE
just change this line:
$fileName = htmlspecialchars($fileName);
to:
$fileName = uniqid() . '_' . microtime();
EDIT 3: TO GET THE CUSTOM SUB DIRECTORY FROM YOUR ADDITIONAL PARAMS
First, make sure than when you create your Upload Dialog from your ExtJS web app, you do this:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_1 : ID_1,
ID_2 : ID_2 // you can put waaay more if you want
}
});
and in your uploadExtJS.php, do this (between the part where you define your new file name and the part where you check for input stream)
$fileName = uniqid() . '_' . microtime();
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$ID_1 = $_GET['ID_1'];
$ID_2 = $_GET['ID_2'];
$newFilePath = $config['upload_dir'] . '/' . $ID_1 . '/' . $ID_2;
if (!file_exists($newFilePath)) {
mkdir($newFilePath, 0777, true);
}
$inputStream = fopen('php://input', 'r');
$outputFilename = $newFilePath . '/' . $fileName;
$realSize = 0;
$data = '';
As you can see, I defined a $newFilePath variable, checked if it was existing before making it, then uploaded to that directory.
Hope this helps anyone who encounters the issue in the future.
I'm trying to get working my upload script.
I'm using CodeIgniter, dropzone.js and Verot_upload class
form:
<form action="/admin/images/upload"
enctype="multipart/form-data" method="post"
class="dropzone"
id="my-awesome-dropzone"></form>
<script src="/skin/js/dropzone.js"></script>
and /admin/images/upload method
public function upload()
{
$data = array();
$this->load->library('verot_upload');
if ($this->authentication->is_loggedin())
{
if (!empty($_FILES))
{
// $tempFile = $_FILES['file']['tmp_name'];
$foo = new Verot_upload($_FILES['file']);
if ($foo->uploaded)
{
// save uploaded image with no changes
$foo->Process('./media/test/');
}
}
} else
{
redirect('/admin/login/', 'refresh');
}
}
it works with regular style:
function upload()
{
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';
$targetFile = $targetPath . $_FILES['file']['name'];
move_uploaded_file($tempFile, $targetFile);
// save data in database (if you like!)
}
}
But not with verot_upload.
So the issue was that, I was trying to upload image as in example at the class initialization.
if I initialize empty class and then use upload method everything works.
/**
* Method for uploading Images from dropdown form.
*
* #param $size
* #param $path
* #param $file
*/
public function upload_image($size, $path, $file)
{
$this->load->library('verot_upload');
$foo = new Verot_upload();
$foo->upload($file);
if ($foo->uploaded)
{
$foo->image_resize = true;
$foo->image_x = $size;
$foo->image_ratio_y = true;
$foo->Process($path);
if ($foo->processed)
{
$new_path = substr($foo->file_dst_pathname,1);
$this
->db
->set('date_created', 'NOW()', false)
->set('path', $new_path, true)
->insert('wysiwyg_img_uploads');
$foo->Clean();
}
}
}
I am using some jquery to help upload a file to a php script. Everything is working fine and the file does in fact get uploaded. But during the upload, I have made it so the file gets resized to our needs, with a new unique file name. I'd like to pass that new unique file name back to the jquery and have it display on the page. Right now, it just displays the original image (which is not resized)
Here's the jquery code:
$(function(){
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
status.text('');
//Add uploaded file to list
if(response==="success"){
$('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
And then my upload php file looks like this:
$uploaddir = 'uploads';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$path = realpath(dirname(__FILE__));
include $path . '/uploads/phmagick.php';
$temp_file = explode(".", $_FILES['uploadfile']['name']);
$time = time();
$new_file = $time . '.' . $temp_file[1];
$p = new phmagick($path . '/uploads/' . $_FILES['uploadfile']['name'], $path . '/uploads/' . $new_file);
$p->convert();
$phMagick = new phMagick($path . '/uploads/' . $new_file, $path . '/uploads/' . $new_file);
$phMagick->debug=true;
$phMagick->resize(414,414,true);
echo "success";
} else {
echo "error";
}
Any thoughts on how I can get the new unique file name back, which would be something like: 1397413326.jpg?
Thank you
Echo the filename back instead of the word "success".