In my Laravel project I created a page to upload the files and I use the $file of laravel it works fine for some system only but for some system it shows an error as shown in image below.
Function I am using to upload files in model
public function add_document_sub_cert($req)
{
$subcontractor_id = $req['subcontractor_id'];
$reference_id = $req['reference_id'];
$files = $req->file("uploaded_doc0");
$i = 0;
foreach($files as $file){
$i++;
$ext = $file->guessClientExtension();
$name = $file->getClientOriginalName();
$file_name_1 = str_replace(".".$ext,"",$name);
$path = $file->storeAs('subcontractor/','avc'.$i.'.jpg');
if($path){
$document = new Document();
$document->doc_name = 'avc.jpg';
$document->module = 'subcontractor';
$document->reference_id = $reference_id;
$document->save();
}
}
}
Your error says that you didn't specify a filename. I see that your variable $file_name_1 is never used. Haven't you forgotten to use it somewhere?
Without knowing how your class Document works, it's impossible to tell you exactly where is the bug.
Related
i'm new in phbp and yii and i have a pronblem with sendind file, i'm using kartik\file\FileInput widget without model and i send to yii controller, where i can get my file from $POST and in first time i used move_uploaded_file with linkt to my file on tmp. The first idea with move doesnt work, i wouldnt find my file on disk, i know is systemd, but i change my tmp folder in php.ini but the file from form doesnt show in this place. This is my conbtroller
$output = "";
$modelZalaczniki = new DelegacjeZalacznikiSearch();
$modelZalaczniki->d_add = date('Y-m-d H:i:s');
$modelZalaczniki->u_add = Yii::$app->user->identity->id;
if (empty($_FILES['file'])){
echo json_encode(['error'=>'Nie znaleziono plik.w.']);
return;
}
$files = $_FILES['file'];
$success = null;
$paths = [];
$fileNames = $files['name'];
if(!file_exists('uploads')){
mkdir('uploads', 0750, true);
}
if(!file_exists('uploads'.DIRECTORY_SEPARATOR.'delegacje')){
mkdir('uploads'.DIRECTORY_SEPARATOR.'delegacje', 0750, true);
}
if(!file_exists('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki')){
mkdir('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki', 0750, true);
}
if(!file_exists('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki'.DIRECTORY_SEPARATOR.$delegacja_id)){
mkdir('uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki'.DIRECTORY_SEPARATOR.$delegacja_id, 0750, true);
}
for($i = 0; $i < count($fileNames); $i++){
$ext = explode('.', basename($fileNames[$i]));
$hashName = md5($fileNames[$i]);
$target = 'uploads'.DIRECTORY_SEPARATOR.'delegacje'.DIRECTORY_SEPARATOR.'pliki'.DIRECTORY_SEPARATOR.$delegacja_id.DIRECTORY_SEPARATOR.$hashName;
// if(file_exists($target)){
// $success = true;
// break;
// }
if(move_uploaded_file($files['tmp_name'][$i], $target)){
$success = true;
$paths[] = $target;
$modelZalaczniki = new DelegacjeZalaczniki();
$modelZalaczniki->delegacja_id = $delegacja_id;
$modelZalaczniki->d_add = date('Y-m-d H:i:s');
$modelZalaczniki->u_add = Yii::$app->user->identity->id;
$modelZalaczniki->sciezka = $target;
$modelZalaczniki->nazwa = $fileNames[$i];
$modelZalaczniki->typ = $ext[1];
$modelZalaczniki->size = $files['size'][$i];
if ($modelZalaczniki->validate()){
$modelZalaczniki->save();
}
}else{
$success = false;
break;
}
Every things work fine but i cant move file to my folder, aha, file is create but in this file is linkt to yii documentation.
Yii 2.0 is great at uploading files. No need for move_uploaded_file.
Take a look at the documentation, and specifically the UploadedFile::getInstance() method.
Useful examples which are relevant to what you're doing are here:
https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
In the above code, when the form is submitted, the yii\web\UploadedFile::getInstance() method is called to represent the uploaded file as an UploadedFile instance. We then rely on the model validation to make sure the uploaded file is valid and save the file on the server.
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.
PHP question on how to return a specific value from another class in a seperate file. So I have created a uploader class to handle and store files uploaded by users. But trying to connect the dots back to the orginal request which if for lets say a specific page - how can i pass a specific value back after I set the values in the other file... code example below.
Thanks Citti
//file 1 //store page request
public function store()
{
//pass the uploaded file to be uploaded and stored
$this->uploader->upload(RequestFile::file('assetfile'));
$page = new Page;
$page->user_id = $asset->user()->id;
$page->assetfile = $file->user_id; <--- ? see below
$page->save();
}
//file 2 //store physical file and create record in DB
class Uploader {
public function upload($file)
{
$extension = $file->getClientOriginalExtension();
$string = str_random(30);
$uploadName = $string . '.' . $extension;
$destinationPath = storage_path() . '/app/uploads/' . Request::user()->id;
$file->move($destinationPath, $uploadName);
$file = new File;
$file->user_id = $asset->user()->id;
$file->assetfile = $uploadId;
$file->save();
$return $file->user_id; ?!?
What you could try is session variables?
Be sure to start sessions on both file 1 and file 2 via:
session_start();
Now, in your upload function, you can declare a session variable
$_SESSION['specificValue'] = $valueSetInUpload;
Now, back on your first file you can access the variable inside of your store function with
$valueSetInUpload = $_SESSION['specificValue'];
I believe this is what you are asking, but I could be wrong.
To return values from a function, you use "return value" and you just have to store that to a variable or output it. Something like:
public function store() {
$fileId = $this->uploader->upload(RequestFile::file('assetfile'));
$page = new Page;
$page->user_id = $asset->user()->id;
$page->assetfile = $fileId;
$page->save();
}
//file 2 //store physical file and create record in DB
class Uploader {
public function upload($file) {
$extension = $file->getClientOriginalExtension();
$string = str_random(30);
$uploadName = $string . '.' . $extension;
$destinationPath = storage_path() . '/app/uploads/' . Request::user()->id;
$file->move($destinationPath, $uploadName);
$file = new File;
$file->user_id = $asset->user()->id;
$file->assetfile = $uploadId;
$file->save();
return $file->user_id;
}
}
I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php
I want to save a file, that I have created in the temp directory, into drupal. But file_save requests a file object but I have just the real path.
$imageId =file_save('/tmp/proj/media/cover.jpg']);
I think you're looking for the file_save_data function, or possibly file_unmanaged_save_data, instead of file_save().
file_save(stdClass $file) save a file object. You are trying to download a file.
You can do as
$file = '/tmp/proj/media/cover.jpg';
// Get the file size
$details = stat($file);
$filesize = $details['size'];
// Get the path to your Drupal site's files directory
$dest = file_directory_path();
// Copy the file to the Drupal files directory
if(!file_copy($file, $dest)) {
echo "Failed to move file: $file.\n";
return;
} else {
// file_move might change the name of the file
$name = basename($file);
}
// Build the file object
$file_obj = new stdClass();
$file_obj->filename = $name;
$file_obj->filepath = $file;
$file_obj->filemime = file_get_mimetype($name);
$file_obj->filesize = $filesize;
$file_obj->filesource = $name;
// You can change this to the UID you want
$file_obj->uid = 1;
$file_obj->status = FILE_STATUS_TEMPORARY;
$file_obj->timestamp = time();
$file_obj->list = 1;
$file_obj->new = true;
// Save file to files table
drupal_write_record('files', $file_obj);
I hope this will help you.