Unable to create the "app/uploads/nameof the folder/1578/3" directory Lravel4 on Digital Ocean server - laravel-4

I my code is throwing error
Unable to create the "app/uploads/Rescom Summit Bangalore 2016/1578/3" directory
if (Input::file($key)->isValid()) {
$destinationPath = 'app/uploads/'.$event.'/'.$userid.'/3'; // upload path
$extension = Input::file($key)->getClientOriginalExtension(); // getting image extension
$name = Input::file($key)->getClientOriginalName();
$curFilesize = Input::file($key)->getClientSize();
$mime =Input::file($key)->getMimeType();
// dd($mime);
//$fileName = $name; // renameing image
//$exstFileSize = Input::file($destinationPath, $fileName);
if (!File::exists($destinationPath."/boq-".$name)){
//creating details for saving inthe file_handler Table
$fileTblObj->user_id = $userid;
$fileTblObj->eventName = $event ;
$fileTblObj->fileName = "boq-".$name;
$fileTblObj->formPage =3 ;
$fileTblObj->filePath = $destinationPath."/";
$fileTblObj->mime= $mime;
$ans->answer_text = 'Yes';
Input::file($key)->move($destinationPath, "boq-".$name); // uploading file to given path
//Input::file($key)->move($boqPath, $boqname); // uploading file to given path
//Save filedetails
$fileTblObj->save();
$ans->save();
Session::flash('success', 'Upload successfully');
}else if(File::size($destinationPath."/".$name) != $curFilesize){
$fileDtls = $fileTblObj->where('uid',$userid)->where('fileName',$name)->where('formPage',3)->first();
Input::file($key)->move($destinationPath, $name);
$ans->answer_text = 'Yes';
$ans->save();
$fileTblObj->where('id',$fileDtls->id)->update(array('updated_at'=>date("Y-m-d h:m:s",time())));
}
//return Redirect::to('upload');
}
Also in the Browser I am getting
protected function getTargetFile($directory, $name = null)
{
if (!is_dir($directory)) {
if (false === #mkdir($directory, 0777, true)) {
throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
}
} elseif (!is_writable($directory)) {
This completely works fine on my local system
I have changed the permission
chmod -R 777 /var/www/laravel/app
Can anyone help me out with this
Thanks

Related

Custom chunk implementation

Is it possible to customize the chunk configuration in Filepond such that the chunk information is provided to the upload server:
as query parameters instead of headers
with custom query parameter names instead of Upload-Length, Upload-Name, and Upload-Offset
I am trying to fit Filepond's chunk implementation to a third party upload endpoint that I don't have control over.
I have found the Advanced configuration where you provide a process function which I've played with a little bit to see what comes through the options param -- however that appears (I think) to make the chunking calculations my responsibility. My original thought was to manipulate the options.chunkServer.url to include the query params I need but I don't believe this processes individual chunks.
In case it makes a difference, this is being done in React using the react-filepond package.
I made and implementation in Laravel 6 using Traits and some "bad practices" (I didn't have time because ... release in prod) to join chunks into a file
Basically:
post to get unique id folder to storage
get chunks and join together
profit!
Here's the full code:
<?php
namespace App\Http\Traits\Upload;
use Closure;
use Faker\Factory as Faker;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait Uploadeable
{
public function uploadFileInStorage(Request $request, Closure $closure)
{
// get the nex offset for next chunk send
if (($request->isMethod('options') || $request->isMethod('head')) && $request->has('patch')) {
//get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// reead all chunks in directory
$patch = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// read offsets for calculate
$offsets = array();
$size = 0;
$last_offset = 0;
foreach ($patch as $filename) {
$size = Storage::size($filename);
list($dir, $offset) = explode('file.patch.', $filename, 2);
array_push($offsets, $offset);
if ($offset > 0 && !in_array($offset - $size, $offsets)) {
$last_offset = $offset - $size;
break;
}
// last offset is at least next offset
$last_offset = $offset + $size;
}
// return offset
return response($last_offset, 200)
->header('Upload-Offset', $last_offset);
}
// chunks
if ($request->isMethod('patch') && $request->has('patch')) {
// get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// read headers
$offset = $request->header('upload-offset');
$length = $request->header('upload-length');
// should be numeric values, else exit
if (!is_numeric($offset) || !is_numeric($length)) {
return response('', 400);
}
// get the file name
$name = $request->header('Upload-Name');
// sleep server for get a diference between file created to sort
usleep(500000);
// storage the chunk with name + offset
Storage::put($dir . 'file.patch.' . $offset, $request->getContent());
// calculate total size of patches
$size = 0;
$patch = Storage::files($dir);
foreach ($patch as $filename) {
$size += Storage::size($filename);
}
// make the final file
if ($size == $length) {
// read all chunks in directory
$files = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// create output file
//Log::info(storage_path('app'));
$new_file_name = $final_name = trim(storage_path('app') . DIRECTORY_SEPARATOR . $dir . $name);
$file_handle = fopen($new_file_name, 'w');
// write patches to file
foreach ($files as $filename) {
// get offset from filename
list($dir, $offset) = explode('.patch.', $filename, 2);
// read chunk
$patch_handle = fopen(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename), 'r');
$patch_contents = fread($patch_handle, filesize(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename)));
fclose($patch_handle);
// apply patch
fseek($file_handle, $offset);
fwrite($file_handle, $patch_contents);
}
// done with file
fclose($file_handle);
// file permission (prefered 0755)
chmod($final_name, 0777);
// remove patches
foreach ($patch as $filename) {
$new_file_name = storage_path('app') . DIRECTORY_SEPARATOR . trim($filename);
unlink($new_file_name);
}
// simple class (no time to explain)
$file = new UploadedFile(
$final_name,
basename($final_name),
mime_content_type($final_name),
filesize($final_name),
false
);
$dir = $request->patch . DIRECTORY_SEPARATOR;
$object = new \stdClass();
$object->full_path = (string)$file->getPathname();
$object->directory = (string)($dir);
$object->path = (string)($dir . basename($final_name));
$object->name = (string)$file->getClientOriginalName();
$object->mime_type = (string)$file->getClientMimeType();
$object->extension = (string)$file->getExtension();
$object->size = (string)$this->formatSizeUnits($file->getSize());
// exec closure
$closure($file, (object)$object, $request);
}
// response
return response()->json([
'message' => 'Archivo subido correctamente.',
'filename' => $name
], 200);
}
// get dir unique id folder temp
if ($request->isMethod('post')) {
$faker = Faker::create();
$unique_id = $faker->uuid . '-' . time();
$unique_folder_path = $unique_id;
// create directory
Storage::makeDirectory($unique_folder_path);
// permisos directorio
chmod(storage_path('app') . DIRECTORY_SEPARATOR . $unique_folder_path . DIRECTORY_SEPARATOR, 0777);
// response with folder
return response($unique_id, 200)
->header('Content-Type', 'text/plain');
}
}
private function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
}
´´´

Intervention \ Image \ Exception \ NotReadableException Unable to init from given binary data

I need to make image from a blob data.I am using Laravel framework and Postman .But in some cases image is not creating and it shows an error Unable to init from given binary data.
My controller function have following code
if ($request->get('logo')) {
$image = $request->get('logo');
$pos = strpos($image, ';');
$type = explode(':', substr($request->get('logo'), 0, $pos))[1];
$type = explode("/", $type);
$name1 = $request->user_id."-".time().'.'.$type[1];
$profile->logo = $name1;
if (!File::exists(public_path().'uploads/profiles/logo')) {
File::makeDirectory(public_path().'uploads/profiles/logo', $mode = 0755, true, true);
}
\Image::make($request->get('logo'))->save(public_path('uploads/profiles/logo/').$name1);
}
$request->get('logo') contain value
data:image/jpeg;base64,/9j/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAQ4B4ADASIAAhEBAxEB/8QAHQAAAQUBAQEBAAAAAAAAAAAAAgADBAUGBwgJAf/EAFwQAAEDAgMGAgYGBwQGBwYBDQIAAwQFEgYiMgcTFEJSYiNyCBUkM4KSFkNTorLCASU0RGNz0jFUYeIJERdkg5MYJjVBRXTwITZRVZSjJ4Sz8hlGVpHTN3GBw+P/xAAbAQADAQEBAQEAAAAAAAAAAAAAAgMEBQEGB//EADoRAAICAQMDAwMCBAUDBAMBAAACAxIEEyIyAQVCERRSIzEzIWIVJEFDNFFhcXIGU5GBg…4V6aSSVCokkkkgCSSSQACkQ43Eu28nMkkvGPFNHGjXhaI5E1UntyO4a+JJJTNLcSpUiNDvzO6Ekl6wik6ywMqAwSSUywCGTJajDcRJJJRGKGZMdk9gKKkkmM4CSSSCQ09/Yo6SSVgO9ejlSrKNU5xD+0Pi0J+X/9NcfxzP8AWWMq3JIr7pRAPlHKkksac2OnP/hkKUEQAkkrHMHgBKy/KkkgBGFmVd49EKNfjqoO/wC6iH30klGf8RfH/Kp2raFMvxbLzaBEPuLyPtCn8Tj+sO3ZAfs+XIkkuBDzNWfxUVNZvdu5FuMKgNjubP0JJLl9yOTHxNQczcjkWCxVWHZLpscgkkkubiCSmfZTqSS7JIkciSSSiRDSSSQA6CaeeSSXi9AIhmkkktgDV5XJXpJJwAvSvSSQBHM86jvGkkqnig3oC0JJIKAJJJLQAlYU0yszaEklOTiBON6wkt8kkuf6dBAr0KSS9AA01MesaSSVlArzkkepMpJLaAkKSSAP/9k=
And on posting data from postman API I got the error
Intervention \ Image \ Exception \ NotReadableException
Unable to init from given binary data.
You should try this:
if ($request->hasFile('logo')) {
$image = $request->file('logo');
$pos = strpos($image, ';');
$type = explode(':', substr($request->get('logo'), 0, $pos))[1];
$type = explode("/", $type);
$name1 = $request->user_id."-".time().'.'.$type[1];
$profile->logo = $name1;
if (!File::exists(public_path().'uploads/profiles/logo')) {
File::makeDirectory(public_path().'uploads/profiles/logo', $mode = 0755, true, true);
}
\Image::make($request->get('logo'))->save(public_path('uploads/profiles/logo/').$name1);
}

Add a warning message: "Image uploaded successfully"

Can you tell me how to add a message, when the image is loaded correctly?
(If you have suggestions on the code I am grateful)
<?
function upload()
{
$result = false;
$alwidth = 1150; // maximum allowed width, in pixels
$alheight = 1150; // maximum allowed height, in pixels
$max_size = 300000; // maximum file size, in KiloBytes
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png'); // allowed extensions
$immagine = '';
$size = 0;
$type = '';
$nome = '';
//check if its allowed or not
$allowtype = array(".jpg",".jpeg",".gif",".png");
if (!(in_array($file_ext, $allowtype))) {
die ('<h1 class=\"cover-heading\">Not allowed extension.<br />Please upload images only</h1>');
}
$type = $_FILES['file']['type'];
$nome = $_FILES['file']['name'];
$immagine = #file_get_contents($_FILES['file']['tmp_name']);
$immagine = addslashes ($immagine);
#include 'config.php';
$sql = "INSERT INTO immagini (nome, size, type, immagine) VALUES ('$nome','$size','$type','$immagine')";
$result = #mysql_query ($sql) or die (mysql_error());
return true;
}
?>
This code will help you to get a message when image uploaded. More info on file uploading can be found here.
$target_dir = "uploads/"; /* Target Folder */
$target_file = $target_dir . basename($_FILES["file"]["name"]); /* Your File Name */
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
/* Checking FILE Type */
if($imageFileType != "jpg" && $imageFileType != "bmp" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
die ('<h1 class=\"cover-heading\">Not allowed extension.<br />Please upload images only</h1>');
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
die ('<h1 class=\"cover-heading\">File Not Uploaded.<br />Please upload images only</h1>');
}
}

access folder outside CodeIgniter

I've been to trying to upload images using code igniter and it works perfectly when the upload folder is just outside of application folder. But my problem is when I try to access folder which is outside whole code igniter folder it is throwing me a error. How to access the folder outside the code igniter folder? I tried $_SERVER['DOCUMENT_ROOT']. But it dint help.
$name = $_POST['name'];
$id = $_POST['id'];
if (isset($_FILES['upload']['name'])) {
// total files //
$count = count($_FILES['upload']['name']);
// all uploads //
$uploads = $_FILES['upload'];
for ($i = 0; $i < $count; $i++) {
if ($uploads['error'][$i] == 0) {
$firstimage = $uploads['name'][$i];
$secondimage = $uploads['name'][$i];
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
$config2['image_library'] = 'gd2';
$config2['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config2['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/thumbnail/'.$uploads['name'][$i];
$config2['maintain_ratio'] = FALSE;
$config2['create_thumb'] = TRUE;
$config2['thumb_marker'] = '_thumb';
$config2['width'] = 75;
$config2['height'] = 50;
$config2['overwrite'] = TRUE;
$this->image_lib->initialize($config2);
$this->load->library('image_lib',$config2);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$config3['image_library'] = 'gd2';
$config3['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config3['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/resize/'.$uploads['name'][$i];
$config3['maintain_ratio'] = FALSE;
$config3['create_thumb'] = TRUE;
$config3['thumb_marker'] = '_thumb';
$config3['width'] = 470;
$config3['height'] = 470;
$config3['overwrite'] = TRUE;
$this->image_lib->initialize($config3);
$this->load->library('image_lib',$config3);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
}
}
$this->load->view('head');
$data = array(
'name' => $name,
'id' => $id
);
After discussing in comments, the problem is likely the move_uploaded_file() function is trying to move the file to a directory that doesn't exist yet.
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
Before the file can be moved the folder needs to be created. If $id is new, it has probably not been created yet. So...
if (!is_dir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id)) {
mkdir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id);
}
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);

How resize image in Joomla?

I try use this:
$image = new JImage();
$image->loadFile($item->logo);
$image->resize('208', '125');
$properties = JImage::getImageFileProperties($item->logo);
echo $image->toFile(JPATH_CACHE . DS . $item->logo, $properties->type);
But not work =\ any idea?
Try this out:
// Set the path to the file
$file = '/Absolute/Path/To/File';
// Instantiate our JImage object
$image = new JImage($file);
// Get the file's properties
$properties = JImage::getImageFileProperties($file);
// Declare the size of our new image
$width = 100;
$height = 100;
// Resize the file as a new object
$resizedImage = $image->resize($width, $height, true);
// Determine the MIME of the original file to get the proper type for output
$mime = $properties->mime;
if ($mime == 'image/jpeg')
{
$type = IMAGETYPE_JPEG;
}
elseif ($mime == 'image/png')
{
$type = IMAGETYPE_PNG;
}
elseif ($mime == 'image/gif')
{
$type = IMAGETYPE_GIF;
}
// Store the resized image to a new file
$resizedImage->toFile('/Absolute/Path/To/New/File', $type);

Resources