Trying to upload file to my test api. For testing I tried to check if input has file and it returns true. The problem is when the code tries to move that file. Search google show almost the same code that I have;
if (Input::hasFile('attachments')) {
$path = base_path().'/assets';
$files = Input::file('attachments');
$data = [];
foreach ($files as $file) {
$data[] = $file->getClientOriginalExtension();
$uuid = Uuid::uuid1();
$extension = $file->getClientOriginalExtension();
$filename = $uuid.'.'.$extension;
$file->move($path, $filename);
}
return Response::json($data);
} else {
return 'no file';
}
Doing a post request using Paw multipart give this result on json
Still can't figure this out. Any help will be much appreciated. Thank you so much guys in advance.
Ok; so something as simple as this [] gave me a hard time figuring things out. All I did is add []; instead of just attachments I did attachments[] as post request name and in my controller I retain the Input::file('attachments')
Thank you guys for your guidance and help. Figured things out the hard and tired way.
I don't know why you are trying to iterate but there is no reason to and $files is a single uploaded file.
Just remove the loop since there is nothing to iterate.
if (Input::hasFile('attachments')) {
$path = base_path().'/assets';
$file = Input::file('attachments');
$uuid = Uuid::uuid1();
$extension = $file->getClientOriginalExtension();
$filename = $uuid.'.'.$extension;
$file->move($path, $filename);
return Response::json($extension);
} else {
return 'no file';
}
If you wanted to have multiple files you would need to have the input setup to be named as an array, attachments[]. You are sending attachments which is always a single value. If you sent an array then there would potentially be something for you to iterate through.
Related
i have a link.when clicking on that link a pdf file will be downloaded. am trying to save that file to a folder. with static name it getting saved,but i want to save with its actual name,is that possible? if anybody knows please help me.
sample url:- http://www.intercoat.de/index.php?option=com_jdownloads&Itemid=206&task=finish&cid=341&catid=178&lang=en
am attaching my code below. i have an array of links like above sample link
so am fetching it from an array
foreach($li as $lm)
{
$i++;
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($lm));
if($mime_type=='application/pdf')
{
echo $lm.$i.'<br>';
$filecontent = file_get_contents($lm);
file_put_contents('./uploads/myfile'.$i.'.pdf', $filecontent);
}
}
now all files not saving with its exact name,it saves as myfile1,myfile2 ..etc
cant take base name because the file name is not in url.that urls are just source of file. anybody knows please help
try this
foreach($li as $lm)
{
$i++;
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($lm));
if($mime_type=='application/pdf')
{
echo $lm.$i.'<br>';
$filecontent = file_get_contents($lm);
$actual_name = basename($lm);
file_put_contents('./uploads/'.$actual_name', $filecontent);
}
}
I am trying to upload same image for multiple students. It works for first one but for next one it gives error.
my code
foreach($student_ids as $key => $student_id) {
$fileIds='';
if(Input::hasfile('attachment')){
$comment = $comments[0];
$file = Input::file('attachment');
$destinationPath = public_path().'/uploads/moments/'.$student_id;
$filename = "moment_".time()."_".trim(rand(1,999)).".".$file->getClientOriginalExtension();
if(is_dir($destinationPath)) {
$upload_success = $file->move($destinationPath, $filename);
}else {
if(mkdir($destinationPath)) {
$upload_success = $file->move($destinationPath, $filename);
}
}
$file = Moment_gallery::create(['image'=>$filename,'comment'=>$comment]);
$fileIds.=$file->id.',';
}
$moments = new moment();
$moments->activity_id = $activity;
$moments->type=$activity_type;
$moments->student_id=$student_id;
$moments->date = $date;
$moments->time = $activity_time ? $activity_time : ' ';
$moments->save();
}
here i am getting array of multiple students id... So i am just uploading same image for those students. It works for single student but then for multiple students it works for first one and give error for second one as
FileException in UploadedFile.php line 235:The file "student.png" was not uploaded due to an unknown error.
whats wrong..? Thank you.
$file = Input::file('attachment');
Understanding that $file is of object type:
Illuminate\Http\UploadedFile
and that it's pointing at the file on the server, e.g.
echo $file->getRealPath(); // /tmp/phpp6HYIk
then you can see that by performing:
$file->move($dest_path);
you're moving the file away from it's original destination thereby making it unavailable for subsequent iterations.
In my images folder have file
1_cover.???
2_cover.???
3_cover.???
4_cover.???
5_cover.???
I wanna get file extension 4_cover.???
How to write PHP code
==========
UPDATE
Thanks for all help me,
I can use this code
$images = glob("./images/4_cover.*");
print_r($images);
Is that what you are looking for ?
$info = new SplFileInfo('photo.jpg');
$path = $info->getExtension();
var_dump($path);
PHP Documentation
If you want to look in a directory for files, this might not be the best suited way to do your method but since you don't know what the file-type is, you can do something like this: (all code should be in order from top-bottom)
The directory housing all of your files
$directory = "public/images/headers/*";
The files gathered from the glob function, use print_r($files) to see all of the files gathered for debugging if there's an error going on
$files = glob( $directory );
The file you said you were looking for, if this is from a database you'll replace this data with data from the database
$filename_to_lookfor = '4_cover.';
If statements to check the file types and see if they're existant
$file_types_to_check_for = ['gif', 'jpg', 'png'];
foreach ($file_types_to_check_for as $filetype)
if (in_array( $filename_to_lookfor.$filetype, $files)
echo "This is a {$filetype} file!";
After reading more into glob - I'm not too experienced with it.
You can simply write this line:
if (count($files = glob( 'public/images/4_cover.*' )) != 0) $file = $files[0]; else echo 'No file with extension!';
or
$file = (count($files = glob('public/images/4_cover.*') != 0)) ? $files[0] : 'NO_FILE' ;
I apologize for the quite bad quality code, but that's what OP wants and that's the easiest way I could think to do that for him.
You can use the pathinfo function
$file = "file.php";
$path_parts = pathinfo($file);
$path_parts['extension']; // return => 'php'
I am building a image upload in Laravel but I keep getting an error inside my foreach loop if one filed is empty.
My upload allows multible images[], so if one field is empty I get an error but I want to allow users to choose if they want to upload eg 2 or 5 images
$input = Input::all();
//Validation
File::exists($path) or File::makeDirectory($path);
foreach($input['images'] as $file) {
$image = Image::make($file->getRealPath()); //getRealPath gives me an error if not all images[] fields from post data containts an image
}
So how can I sort my input images[] from empty inputs?
Thanks in advance,
If I understood well you need something like this:
if(empty($file)) {
unset($file);
}
or something like this:
if(!empty($file)){
$image = Image::make($file->getRealPath());
}
Try checking whether $file has a non-null value before running getRealPath
File::exists($path) or File::makeDirectory($path);
foreach($input['images'] as $file) {
if($file) {
$image = Image::make($file->getRealPath());
}
}
By the way, $image is reset with every iteration. Is that really what you want? Do you care which $image you get?
You can use array_filter() with no callback to remove all elements that have a falsy value:
$input = array_filter($input);
foreach($input['images'] as $file) {
$image = Image::make($file->getRealPath());
}
What I did to solve it was to add if check within my foreach loop and it worked. But im not sure if this is the best solution?
$input = Input::all();
foreach($input['images'] as $file) {
if($file == ""){ //If one input is empty it jumps over it, instead of trying to use getRealPath() on an empty value
break;
}
$image = Image::make($file->getRealPath());
}
In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}