beforeSave() to rename the file in yii(php) - yii

I am using beforeSave() to rename the file thats been uploaded. but its not getting renamed before save into the folder. it has the same name as uploaded one.Iam using extension EAjaxUpload for uploading the file. can anyone help me where i have gone wrong... And i am working on windows.
In Model(AttachResume):-
protected function beforeSave()
{
$path='C:\\wamp\\www\\Myapp\\Resumes\\';
$uid=$_POST['AttachResume']['User_id'];
//var_dump($this->User_id); exit();
$file=$_POST['AttachResume']['ResumeName'];
//var_dump($this->ResumeName); exit();
$temp = $path.$file;
$newname=$uid.$file;
if(file_exists($temp)==true)
{
rename($temp, $path.$newname);
}
return parent::beforeSave();
}
Controller:-
public function actionIndex()
{
$model=new AttachResume;
if(isset($_POST['AttachResume']))
{
$model->User_id=$_POST['AttachResume']['User_id'];
$model->ResumeName=$_POST['AttachResume']['ResumeName'];
$model->save();
}
$this->render('index',array('model'=>$model));
}
Myapp is the aplication.Resume is the folder under it where i have to save documents,
Thanks

Use this extension:
http://www.yiiframework.com/extension/eajaxupload/
Thats the best extension available
To rename the file being uploaded add this line below:
rename($folder.$result['filename'],$folder."newfilename");
Thanks to Ben:
Solution found on this link:
How to use xupload with Yii

Related

symfony 4 Upload

How to upload a file in symfony 4.I have done with the symfony document. I don't know where I have missed something. Its throws error while uploading file give me some clues
REFERED LINK:
https://symfony.com/doc/current/controller/upload_file.html
ERROR:
The file "" does not exist
Entity
public function getBrochure()
{
return $this->brochure;
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
File upload Listener
class FileUploader
{
private $targetDirectory;
public function __construct($targetDirectory)
{
$this->targetDirectory = $targetDirectory;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getTargetDirectory(), $fileName);
return $fileName;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
}
This Symfony tutorial works fine for me so I'll try to explain how and perhaps it will help you or people still looking for an answer, this post getting a bit old.
So first you have to create the FileUploader service in App\Service for better reusability (chapter: Creating an Uploader Service). You can basically copy/paste what they've done here, it works like a charm. Then you need to open your services.yaml in Config folder and explicit your brochure directory:
parameters:
brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
# ...
services:
# ...
App\Service\FileUploader:
arguments:
$targetDirectory: '%brochures_directory%'
Now everything is normally ready to use your FileUploader service.
So if you're in your controller (for example), I guess you want to use it in a form. Thus, you just have to do this (don't forget to use your Service in your Controller):
public function myController(FileUploader $fileUploader)
{
// Create your form and handle it
if ($form isValid() && &form isSubmitted()) {
$file = $myEntity->getBrochure();
$fileName = $this->fileUploader->upload($file);
$myEntity->setBrochure($fileName);
// Form validation and redirection
}
// Render your template
}
One important point I forgot to say. In your FormType, you need to say that the Brochure will be a FileType:
$builder->add('brochure', FileType::class)
But in your entity you have to specify your brochure is stored as a "string":
/**
* #MongoDB\Field(type="string")
*/
protected $brochure;
The reason is your file is getting uploaded and saved in your public/uploads/brochure. But your database is only remembering a string path to reach it.
I hope this will help!

Custom Sendinblue API available for CodeIgniter?

I am searching for a SendinBlue API for Codeigniter but not found yet.
In the case that the API does not exists yet, is that hard to code it by myself (I already know HTTP requests but I not have any idea about configs)
Or is that possible to use the PHP one ?
Thanks
I have a beautiful solution for this and it works fine for me and I hope it will work for you as well.
I am using API-v3.
What I did is:
Downloaded the API through composer on my local PC.
Created a folder named "sendinblue" on the server (where we have
assets folders) and upload the vendor folder from the downloaded API
inside this folder.
Created a library named "Sendinblue.php" and added all the necessary functions here. Now I can use this library like other libraries.
This is my library structure:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Sendinblue{
public $config;
public $apiInstance;
public function __construct(){
require_once('sendinblue/vendor/autoload.php');
$this->config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', '');
$this->apiInstance = new SendinBlue\Client\Api\ContactsApi(
new GuzzleHttp\Client(),
$this->config
);
}
public function get_contact_info($data){
$identifier = $data['email'];
try {
return $result = $this->apiInstance->getContactInfo($identifier);
} catch (Exception $e) {
return 'Exception when calling ContactsApi->getContactInfo: '.$e->getMessage();
}
}
public function create_contact($data){
$createContact = new \SendinBlue\Client\Model\CreateContact();
$createContact['email'] = $data['email'];
$createContact['listIds'] = [2];
try {
return $result = $this->apiInstance->createContact($createContact);
} catch (Exception $e) {
return $e->getCode();
}
}

Unable to change file name after File Upload using WebApi MultipartFormDataStreamProvider

Im using WebApi to upload a file, but when I run
request.Content.ReadAsMultipartAsync(provider)
The file is uploaded but its file name is totally changed.
I read something about that says that it is automatically made for security reasons. Anyway I want to store the file with the real file name. Any idea how to do it?
This simple override fix this issue
public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyMultipartFormDataStreamProvider(string path) : base(path)
{ }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
// override the filename which is stored by the provider (by default is bodypart_x)
string originalFileName = headers.ContentDisposition.FileName.Trim('\"');
return originalFileName;
}
}

Cuploadfile instance not compared to null although no file instance is provided?

public function actionCreate()
{
$model=new Patient('patientScenario');
if(isset($_POST['Patient']))
{
$model->attributes=$_POST['Patient'];
$model->image= CUploadedFile::getInstance($model,'image');
if($model->save())
{
$imagePath = Yii::app()->params['DataFolder'];
if($model->image!="")
{
if(!(file_exists($imagePath)))
{
mkdir($imagePath,'0777',true);
}
}
$model->image->saveAs($imagePath.$model->id.'_'.$model->image->name);
$ns=new newserver(); $ns->uploadFile($filepath,$imagePath.$model->id.'_'.$model->image->name, $model->id.'_'.$model->image->name);
}
}}
It is a action with lot of codes I have simplified it to focus on the issue here.
The issue is while creating a patient, If I upload a image its working fine, But even though I don't upload an image the condition $model->image!="" became true and obviously there will be no file name and while trying to upload on the new server class I get
fopen(22522_): failed to open stream: No such file or directory
I tried ($model->image!==NULL) as well. still getting the same error.
But it works fine in my localhost, But not in the server.
Your problem is on newserver() class
On that class you are tried to open a file .
Check condition before the file open on newserver() class
or give a code on newserver Class

UploadField for Files in SilverStripe

I want to insert a new field, below the content textarea, to hold a link/connection to one file (moastly a zip file from my assets folder).
I couldn't find any documentation nor a tutorial for files. Only images. Does anybody know where I can find some help files or can give me some basic code to start from?
In general, there's the API Docs for UploadField.
As well as the docs,
although they're a bit hidden - I'm just fixing the search on doc.silverstripe.org.
This should do the trick:
<?php
class Page extends SiteTree {
static $has_one = array('MyFile', 'File');
function getCMSFields() {
$fields = parent::getCMSFields();
$upload = new UploadField('MyFile');
$upload->setConfig('allowedMaxFileNumber', 1);
$upload->getValidator()->setAllowedExtensions(array('zip'));
$fields->addFieldToTab('Root.Main', $upload);
return $fields;
}
}