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;
}
}
Related
I'm create project CRUD with uploads file using json_encode for uploads file in database. i want to ask how to edit/update json field in database laravel ?
i try using isset($data)? json_encode($data): $sid->file_uploads in public function update() but that code when i update can be replace previous file.
$sid = Sid::find($id);
if($request->file('file_uploads'))
{
foreach($request->file('file_uploads') as $file)
{
$name = $file->getClientOriginalName();
$path = 'public/file/'.$sid->employee_name;
$file->move($path, $name);
$data[] = $name;
}
}
$sid->employee_sid = $request->employee_sid;
$sid->employee_npk = $request->employee_npk;
$sid->employee_name = $request->employee_name;
$sid->file_uploads = isset($data)? json_encode($data): $sid->file_uploads;
$sid->save();
i expect the result is file when i upload will add file in DB. for example i uploads 5 file but when i create i just uploads 2 file and when i want to edit i add 3 file and totals file is 5 in DB.
This can resolve, php in the new versions does not support creation of var at runtime, or its if that checks if it has files is resulting in false.
$sid = Sid::find($id);
$data = [];
if($request->file('file_uploads'))
{
foreach($request->file('file_uploads') as $file)
{
$name = $file->getClientOriginalName();
$path = 'public/file/'.$sid->employee_name;
$file->move($path, $name);
$data[] = $name;
}
}
$sid->employee_sid = $request->employee_sid;
$sid->employee_npk = $request->employee_npk;
$sid->employee_name = $request->employee_name;
$sid->file_uploads = count($data)? json_encode(array_merge(json_decode($sid->file_uploads, true),$data)): $sid->file_uploads;
$sid->save();
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.
I have made a form on the front end to upload some images. My idea is to automatically rename all files uploaded into unique id's.
I have looked at the SilverStripe API and I do not see anything about that. UploadField API
Is this possible?
Here is my solution bellow, in Silverstripe 3.X we must extend UploadField with another class. Then copy the ''saveTemporaryFile'' function into it.
Just before ''try'', just have to add :
$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];
Results :
class RandomNameUploadField extends UploadField {
protected function saveTemporaryFile($tmpFile, &$error = null) {
// Determine container object
$error = null;
$fileObject = null;
if (empty($tmpFile)) {
$error = _t('UploadField.FIELDNOTSET', 'File information not found');
return null;
}
if($tmpFile['error']) {
$error = $tmpFile['error'];
return null;
}
// Search for relations that can hold the uploaded files, but don't fallback
// to default if there is no automatic relation
if ($relationClass = $this->getRelationAutosetClass(null)) {
// Create new object explicitly. Otherwise rely on Upload::load to choose the class.
$fileObject = Object::create($relationClass);
}
$ext = array_reverse(explode('.',$tmpFile['name'])); // explode filename into array, reverse array, first array key will then be file extension
$tmpFile['name'] = hash_hmac('sha256', $tmpFile['name'], '12345') . '.' . $ext[0];
// Get the uploaded file into a new file object.
try {
$this->upload->loadIntoFile($tmpFile, $fileObject, $this->getFolderName());
} catch (Exception $e) {
// we shouldn't get an error here, but just in case
$error = $e->getMessage();
return null;
}
// Check if upload field has an error
if ($this->upload->isError()) {
$error = implode(' ' . PHP_EOL, $this->upload->getErrors());
return null;
}
// return file
return $this->upload->getFile();
}
}
Thanks #3dgoo to give me a part of the solution!
I don't now about a API but with some code I was able to do that.
You have two possibilities.
First using database.
Second using only code:
$directory = '/teste/www/fotos/';
$files = glob($directory . '*.jpg');
if ( $files !== false )
{
$filecount = count( $files );
$newid = $filecount+1;
$new_name = "foto_".$newid;
$target_file = $directory."/".$new_name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
else
{
$new_name = "foto_1";
$target_file = $directory."/".$new_name;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
My example is for jpeg but you can look for hall types.
I am trying to save fine path in database and save image file in folder but I want to save file with unique name. How to do that?
My controller is :
$image = $request->photo;
//$photoname_path = 'images'.$date.'/'.$image->getClientOriginalName();
$image->move('images',$image->getClientOriginalName());
$photoname = 'images/'.$image->getClientOriginalName();
$adduser = new Employee;
$adduser->name = $request->name;
$adduser->photo = $photoname;
$adduser->email = $request->email;
$adduser->contact_no = $request->contact_no;
$adduser->pan_no = $request->pan_no;
$adduser->department = $request->department;
$adduser->position = $request->position;
$adduser->save();
return redirect()->back();
I was trying to save it with time but I failed. How to do it?
I see that you have access to the request object so, try this:
$photo = $request->file('photo');
$photoName = time() . '_' . $photo->getClientOriginalName();
$photo->move('images', $photoName);
Laravel 4.2 upload file success but not found when I used it
The file uploaded succesfully on the directory I've been specified, but when I want to display it, it return not found, but if I change it to other file name in the same directory, it appears. What's wrong?
here is my code:
app/services/CommonProvider.php
<?php
class CommonProvider{
# simple class to provide static common functions
public static function uploadFiles($filename,$name,$location = 'img/'){
if(Input::hasFile($name)){
$filename .= '.'.Input::file($name)->getClientOriginalExtension();
$filename = $location . $filename;
if(Input::file($name)->move($location, $filename))
return $filename;
return false;
}
return false;
}
}
and here is the updateUser method (for example) from app/services/UserProvider.php
public function updateUser($input, $user_id) {
$validation_messages = $this->validateUser(Input::all(), false);
if ($validation_messages !== true) return $validation_messages;
try {
$insert = $this->user->find($user_id);
$insert->access_level = $input['access_level'];
$insert->email = $input['email'];
$insert->name = $input['name'];
$insert->mobile_no = $input['mobile_no'];
if ($input['password'] != '') $insert->password = Hash::make($input['password']);
if (!isset($input['active_status'])) $insert->active_status = 0;
$insert->save();
$filename = CommonProvider::uploadFiles($insert->id, 'user_image', 'img/user_images/');
if ($filename) {
$insert->user_image = $filename;
}
$insert->save();
return true;
}
catch(Exception $e) {
dd($e);
return false;
}
}
What do I miss?
You shouldn't add path to your filename when moving the file (you can add it when you want to retrieve the file).
$filename = $location . $filename; // remove this line
And I think you need to add absolute path so you will know exactly where the uploaded file is moved to.
In this code I added public_path()
$abslocation = public_path() . '/'. $location;
if(Input::file($name)->move($abslocation, $filename))
return $location . $filename;