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.
Related
I am trying to upload a .qif file in php codeigniter but it returns an error
The filetype you are attempting to upload is not allowed.
When I try to upload another type file (PDF, CSV, docs, etc.) they upload successfully.
Here is my code:
function do_upload($field_name, $files, $folder_path,$save_name="",$prefix="bk_"){
$ci = & get_instance();
//create upload folder if not exists
if (!is_dir($folder_path)) {
mkdir($folder_path, 0777, TRUE);
}
$save_name = $prefix.time()."_".$files['name'];
$data = array();
$config = array();
$config['upload_path'] = $folder_path;
//$config['max_size'] = 0;
$config['allowed_types'] = 'csv|CSV|txt|TXT|pdf|PDF|zip|ZIP|doc|DOC|docx|DOCX|xlsx|xls|XLS|XLSX|QIF|qif';
$config['file_name'] = $save_name;
$ci->load->library('upload');
$ci->upload->initialize($config);
// echo "hello 1"; die;
if ($ci->upload->do_upload($field_name)){
$data = $ci->upload->data();
$data['status'] = 1;
}
else{
$data['status'] = 0;
$data['error'] = $ci->upload->display_errors();
}
return $data;
}
You get the "filetype is not allowed" error, because the original Codeigniter mime-type configuration file doesn't list an qif entry:
in your config/mimes.php file add to the $mimes array this line:
'qif' => 'application/qif'
and eventually
'qif' => 'image/x-quicktime'
mime-type source: http://fileformats.archiveteam.org/wiki/Ext:qif
the native php move_uploaded_file method without checking for mime-types can turn into a security problem
I got a solution after lot of searches
I just use move_uploaded_file function and it's work
move_uploaded_file($_FILES["file"]["tmp_name"], $path);
if someone have a better answer answer please share that.
thanks
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've recently created a page on our site where users can upload an image and email it to an email address set up specifically to keep the uploaded documents.
I've tested this myself and it works, with the attachments arriving in gmail as expected.
However, whenever someone from outside uses this feature the attachment in the email is unavailable, or not could not be loaded, when we try to open it.
The code is split between 2 files, a controller and a helper. Here's the code (For the sake of saving some space I've removed all error checks, but in the actual code they are all still in place and not picking up any errors whatsoever):
controller
$helper = [GET HELPER];
/** Upload the file to a temp location so that we can attach it to an email */
$uploader = new Varien_File_Uploader('filename');
$uploader->setAllowedExtensions(array(
'image/jpeg',
'image/jpg',
'image/png',
'application/pdf'
))
->setAllowRenameFiles(true)
->setFilesDispersion(false);
$path = $helper->getFileStorageLocation(); // Will store files in /tmp
if (!is_dir($path))
{
mkdir($path, 0775, true);
}
$uploader->save($path, $_FILES['filename']['name']);
$result = $helper->sendMail($_FILES['filename']['name']);
if ($result)
{
$uploadSuccess = true;
/** Remove the temp file */
unlink($path . DS . $_FILES['filename']['name']);
}
helper
/** Declare variables */
$order = Mage::getModel('sales/order')->load($orderId);
$file_incremented_id = $order->getIncrementId();
$copyTo = $this->getCopyTo();
$copyFrom = $this->getCopyFrom();
$subject = 'proof of upload for ' . $file_incremented_id;
$copyTo = explode(',', $copyTo);
$body = '<span>Please see attachment</span>';
$file = $this->getFileStorageLocation() . DS . $filename; // function receives filename from whatever is calling it
$attachment = file_get_contents($file);
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (!$copyTo)
{
return false;
}
$mail = Mage::getModel('core/email_template');
$mail->setSenderName('Uploader');
$mail->setSenderEmail($copyFrom);
$mail->setTemplateSubject($subject);
$mail->setTemplateText($body);
$mail->getMail()->createAttachment(
$attachement,
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
$file_incremented_id . '.' . $extension // Set order number as file name
);
try
{
$mail->send($copyTo);
return true;
}
catch (Exception $e)
{
return false;
}
Can anyone see anything that might be causing the issue, or think of what it might be based on my explanation of the setup?
So the problem, in the end, was filesize. My fault for not posting the $_FILES variable.
I saw it a bit later and the variable had error = 1, meaning that the file's size was larger than what was allowed by the max_upload_filesize in the php.ini
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.