I am using cakephp 2.1 and i am trying to upload files and how can i retrive the extension of the file.
Database/users
Id Auto_Increment
username
file_name
Controller/UsersController.php
public function register(){
if ($this->request->is('post')){
$filename = $this->data['User']['file_name']['name'];
//$temp_ext = $this->data['User']['resume_file']['ext'];
$this->Session->setFlash('Extension : ' . $temp_ext);
}
}
When tried the above code, to get extension. it only gives single letters like L, r ie firt character of the filename but not extension
Now how can i get the extension of the file.. i gone through this link
http://api.cakephp.org/class/file
but could not understand to retrieve the file.
Adding a Debug report to #Julian Hollmann
array(
'User' => array(
'file_name' => array(
'name' => '550992_234300256686731_213914803_n.jpg',
'type' => 'image/jpeg',
'tmp_name' => 'D:\xampp\tmp\php866F.tmp',
'error' => (int) 0,
'size' => (int) 42292
)
)
)
First of all, your data should be in $this->request->data
If you want to see what's in there, just do debug($this->request->data);
Edit:
The correct answer is:
$filename = $this->request->data['User']['file_name']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
See also php manual
$filename = $this->data['User']['file_name']['name'];
$this->request->data['User']['file_name'] = $filename;
$fileExt = explode(".", $filename);
$fileExt2 = end($fileExt);
Try this one... it will give you extension
Related
Here below is the kartik file input widget in update_form.
echo FileInput::widget(
[
'name' => 'BriefRequirements[requirement_value][]',
'attribute' => 'assets_file',
'id' => 'assets_file',
'options' => ['multiple' => true],
'pluginOptions' => [
'overwriteInitial' => false,
'initialPreview' => $image_url,
'deleteUrl' => ' site/delete',
'initialPreviewAsData' => true,
'initialPreviewFileType' => 'image' //'pdf'
]
]
);
below is multiple image loading code,
foreach ($modelRequirements as $req) {
$image_url[] = Yii::$app->request->baseUrl
. '/theme/business_campaign_files/'
. $req['requirement_value'];
}
I need help with my two questions:
Need to show all selected format files like image, pdf, doc etc [I tried to like 'initialPreviewFileType'=>'any'] not working.
I want to pass the selected image id to action to delete the image? - 'deleteUrl' => ' site/delete','id'=>12, <-- like this.
In the below code i got the result for my two questions.
$initializeConfig = [];
$initializeConfig1 = [];
if ($modelRequirements) {
foreach ($modelRequirements as $req) {
$extension = substr(
$req['requirement_value'],
strrpos($req['requirement_value'], '.') + 1
);
$image_url[] = Yii::$app->request->baseUrl
. '/theme/business_campaign_files/'
. $req['requirement_value'];
$initializeConfig1['url'] = Url::toRoute('delete-requirement');
$initializeConfig1['key'] = $req['id'];
$initializeConfig1['type'] = $type;
array_push($initializeConfig, $initializeConfig1);
}
}
In the above code i got the result for my two questions.
For delete -> mentioned url I wrote the delete function, also through key parameter I passed the id.
For view all the extension files u have to send like "type" $initializeConfig1['type'] = $type; in the type variable i am getting the image extension based on the extension i am setting the format of the file like[pdf,xlsx,image].
easyOne
Various methods to manage your preview. The following features are demonstrated in this example:
For Single Image you can make it Multiple Same as
$files = array();
$files['initialPreview'] = Url::base(TRUE) . '/' . $uploadurl . $newFileName;
$files['initialPreviewAsData'] = true;
//FOR PDF
if ($fieldtype == 'pdf') {
$files['initialPreviewConfig'][] = array('type' => 'pdf', 'key' => $newFileName);
} else {
//FOR IMAGES
$files['initialPreviewConfig']['key'] = $newFileName;
}
$files['namefile'] = $newFileName;
JSON Response :
{
"initialPreview": "http://localhost/yii2/uploads/project/brochure/fileone.pdf",
"initialPreviewAsData": true,
"initialPreviewConfig": [
{
"type": "pdf",
"key": "fileone.pdf"
}
],
"namefile": "fileone.pdf"
}
I working on a project with PHP Codeigniter. I want to upload an image, change the name of the image and store it in database (with extension). I have written the following code. It works perfectly but the problem is that the image name is stored without its extension in database. For example, when I run the code, the name that is stored in database is 'imagename', instead of 'imagename.jpg' or 'imagename.png'. I want to store the complete name with extension.
This is my Controller
public function FunctionName()
{
$fname = ucwords($this->input->post('fname'));
$lname = ucwords($this->input->post('lname'));
$prof_pic = $_FILES['profile_pic']['name'];
$config = array ('upload_path' => './images/students/',
'allowed_types' => "jpeg|jpg|png",
'overwrite' => TRUE,
'file_name' => $fname."_".$lname,
'remove_spaces' => TRUE,
'file_ext_tolower' => TRUE
);
$this->load->library('upload', $config);
$this->upload->do_upload('profile_pic');
$image_name = $config['file_name'].".".$config['file_type'];
$data = array('std_fname' => $std_fname,
'std_lname' => $std_lname,
'profile_pic' => $image
);
$this->General_Model->create_record($data, "table_name");
}
To get uploaded file name use
$this->upload->data('file_name');
AS
$this->upload->do_upload('profile_pic');
$image_name = $this->upload->data('file_name');
Read Information about the uploaded file
Try with the below code
$prof_pic = $_FILES['profile_pic']['name'];
$newName = "<Desired name>".".".pathinfo($prof_pic, PATHINFO_EXTENSION);
$config = array ('upload_path' => './images/students/',
'allowed_types' => "jpeg|jpg|png",
'overwrite' => TRUE,
'file_name' => $newName,
'remove_spaces' => TRUE,
'file_ext_tolower' => TRUE
);
the line
$newName = "<Desired name>".".".pathinfo($prof_pic, PATHINFO_EXTENSION);
Will assign the new name with the file extension of the actual file
Edit: It turns out this issue happens while trying to upload .sql files. It's not the file name.
When I try to upload a file with this name: forge_2016-02-08_--USERS THOUGH.sql I'm shown this error below:
ErrorException in FileinfoMimeTypeGuesser.php line 69:
Array to string conversion
and
at HandleExceptions->handleError('8', 'Array to string conversion', '/home/forge/example.com/vendor/symfony/http-foundation/File/MimeType/FileinfoMimeTypeGuesser.php', '69', array('path' => '/tmp/phppkDGK8', 'finfo' => object(finfo)))
at finfo->file('/tmp/phppkDGK8') in FileinfoMimeTypeGuesser.php line 69
at finfo->file('/tmp/phppkDGK8') in FileinfoMimeTypeGuesser.php line 69
at FileinfoMimeTypeGuesser->guess('/tmp/phppkDGK8') in MimeTypeGuesser.php line 139
I have no idea why this error is happening. Here's my upload code:
$baseDir = storage_path('uploads');
$file = $request->file('file');
$mimeType = $file->getMimeType();
$name = str_random(6) . time() . '-' . str_replace(' ', '_', Str::ascii($file->getClientOriginalName()));
$file->move($baseDir, $name);
$path = $baseDir . '/' . $name;
$data = ['path' => $path, 'ip' => userIP(), 'name' => $file->getClientOriginalName(), 'mime' => $mimeType, 'size' => $file->getClientSize()];
$status = Uploads::create($data);
if ($status) {
$su = true;
Please help guys. I don't know why this is happening.
I fixed it by changing
$mimeType = $file->getMimeType();
to
$mimeType = $file->getClientMimeType();
This fixed it.
before it, i use other function to upload excel data with codeigniter to mysql, but show error the file path is not readable, and then i use this code to upload excel data
//setting excel reader
error_reporting(E_ALL ^ E_NOTICE);
error_reporting(0);
require_once 'include/excel_reader.php';
$get_periode = $this->input->post("periode");
$data = new Spreadsheet_Excel_Reader($_FILES['userfile']['tmp_name']);
$count = 0;
//read excel
foreach($data->dump(false,false,false,false) as $row){
$value = $this->ruas_jalan_model->get_by(array("NAMA_KOTA"=>$row["NAMA_KOTA"]),FALSE,FALSE,TRUE);
$data2 = array(
"ID_PERIODE" => $get_periode,
"NAMA_KOTA" => $value["NAMA_KOTA"],
"NO_RUAS1" => $value["NO_RUAS1"],
"NO_RUAS2" => $value["NO_RUAS2"],
"NO_RUAS3" => $value["NO_RUAS3"],
"NAMA_RUAS" => $value["NAMA_RUAS"],
"PANJANG" => $value["PANJANG"],
"HOTMIX_BAIK" => $value["HOTMIX_BAIK"],
"HOTMIX_SEDANG" => $value["HOTMIX_SEDANG"],
"HOTMIX_RR" => $value["HOTMIX_RR"],
"HOTMIX_RB" => $value["HOTMIX_RB"],
"LAPEN_BAIK" => $value["LAPEN_BAIK"],
"LAPEN_SEDANG" => $value["LAPEN_SEDANG"],
"LAPEN_RR" => $value["LAPEN_RR"],
"LAPEN_RB" => $value["LAPEN_RB"],
"LPC" => $value["LPC"],
"TANAH" => $value["TANAH"],
"HUTAN" => $value["HUTAN"],
"LANG" => $value["LATITUDE"],
"LOT" => $value["LOTITUDE"]
);
$this->ruas_jalan_model->save($data2);
$count++;
}
but i still get error not readable, and i don't know why, this is the error code
The filename C:\xampp\tmp\php4632.tmp is not readable
whats wrong ?
the problem is library couldn't read excel with extension xlsx (ms.office 2007 -> ) , and then i use xls (ms.office 2003)
How to show the file upload name for jQuery Multiple File Upload Plugin v1.48?
After the users have uploaded the file, is there a way to show the file that they have uploaded under the profile?
1.if ( isset($_FILES['tb-documents']) ) {
$documents = $_FILES['tb-documents'];
foreach ( $documents['name'] as $key => $value ) {
if ( $documents['name'][$key]) {
$document = array(
'name' => $documents['name'][$key],
'type' => $documents['type'][$key],
'tmp_name' => $documents['tmp_name'][$key],
'error' => $documents['error'][$key],
'size' => $documents['size'][$key]
);
$status = wp_handle_upload($document, array('test_form' => false));
if( !isset($status['error']) ) {
$uploads = wp_upload_dir();
add_user_meta($user->ID, 'tb-documents', $uploads['url'].'/'.basename($status['file']));
}
}
}
}
The upload is working well on the user profile. However, I want to pull out the file name that they have uploaded and display all the uploaded file names to them.
Which variable should I use?
1.I tried this, $content .= '.$documents['name']'; but it doesn't work. It shows syntax error.
You have to combine results from this $documents['name'][$key] and show it to user.
For example:
if (isset($_FILES['tb-documents'])) {
$uploadedFiles = array();
$documents = $_FILES['tb-documents'];
foreach ($documents['name'] as $key => $value) {
if ($documents['name'][$key]) {
$document = array(
'name' => $documents['name'][$key],
'type' => $documents['type'][$key],
'tmp_name' => $documents['tmp_name'][$key],
'error' => $documents['error'][$key],
'size' => $documents['size'][$key]
);
$status = wp_handle_upload($document, array('test_form' => false));
if (!isset($status['error'])) {
$uploads = wp_upload_dir();
add_user_meta($user->ID, 'tb-documents', $uploads['url'] . '/' . basename($status['file']));
$uploadedFiles[] = $documents['name'][$key];
}
}
}
var_dump(implode(", ", $uploadedFiles));
}
If you want to show the uploaded files to the uploader, you can handle it easily in JQuery using the fileuploaddone callback provided by jQuery uploader
$('#fileupload')
.bind('fileuploaddone', function (e, data) {
console.log( data['result']['files'][0]['name'] );
console.log( data['result']['files'][0]['url'] );
});
If you have multiple files, you need to loop over data['result']['files'] array.