I want upload video in my Yii form
I try this:
$dbimage = '';
if (null != $patientmodel->treatment_videos) {
$filename = uniqid() . '.' . $patientmodel->treatment_videos->extension;
$patient_videos->saveAs($patientmodel->patientImgPath . '/' . $filename);
$dbimage .= $filename . ',';
$dbimage = rtrim($dbimage, ',');
$patientmodel->treatment_videos = $dbimage;
}
output:I cannot select my video files
from UploadedFile class the easy sample code is:
view.php
<?= Html::beginForm('', 'post', ['enctype' => 'multipart/form-data']) ?>
<?= Html::fileInput('attachment', '', ['id' => 'attachment']) ?>
<?= Html::submitButton('Submit') ?>
<?= Html::endForm() ?>
controller.php
if ($file = UploadedFile::getInstanceByName('attachment')) { // check if file uploaded
if (in_array($file->extension, ['mp3', 'wav'])) { // check valid audio file extensions
$file_size_limit = 1024 * 1024 * 10 // 10mb
if ($file->size < $file_size_limit) { // check max file size
$path = 'path/to/directory';
if ($file->saveAs($path)) {
return 'file uploaded successfully';
}else{
return $file->error;
}
}
}
}
maybe you see this problems in your file uploadings:
increase upload_max_filesize
increase max_execution_time
or for using in models you can use input Uploading Files document
Related
I'm using this code to upload files or images. It's working but can't upload a large file and I want to upload a file when selecting it from the local computer like the below image.
I use below PHP code in the controller.
$image = $request->file('file_upload');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
echo $new_name;
$image->move(public_path('images'), $new_name);
Try to use this code.
Change the $request->sharing_file with your field name.
You can increase the $size for image what you want, currently it is 16mb and working fine.
$myimage = $request->image;
$size = getClientSize();
if($sizes < 16777216){
$fileMimeType = explode('/', $myimage->getClientMimeType());
$fileType = $fileMimeType[0];
$originalFileName = substr($myimage->getClientOriginalName(), 0, strpos($myimage->getClientOriginalName(), "."));
$originalFileName = substr(str_replace(' ', '-', $originalFileName),0,10);
$rand = rand(9,1000);
$fileName = $rand.'-'.$originalFileName.'.'.$myimage->getClientOriginalExtension();
$upload = $values->move(public_path('images'), $fileName);
if($upload) {
$message = 'File Uploaded';
} else {
$message = "Failed to upload file";
}
}
else {
$message = 'Files size should be less than 16 MB.';
}
Try
if ($request->hasFile('file_upload')) {
$destinationPath = public_path().'/images/';
$file = $request->file_upload;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['your_databse_table_field_name'] = $fileName;
}
I am uploading file into folder using PHP but my issue is its at a time writing file into 2 different path. My code is below.
if(array_key_exists('pimage',$_FILES)){
$tempFile = $_FILES['pimage']['tmp_name'];
$fileName = $_FILES['pimage']['name'];
$fileName = str_replace(" ", "-", $_FILES['pimage']['name']);
$fig = rand(1, 999999);
$saveFile = $fig . '_' . $fileName;
$uploadOk = 1;
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_GIF) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
}
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_JPEG) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromjpeg($_FILES['pimage']['tmp_name']), $saveFile);
}
if (strpos($fileName,'php') !== false) {
# code...
}else{
$targetPath = PT_USERS_IMAGES_UPLOAD;
$targetFile = $targetPath . $saveFile;
if (file_exists($targetFile)) {
$data=array("msg"=>'profile image already exists');
$uploadOk = 0;
}
if ($_FILES["pimage"]["size"] > 2000000 || $_FILES["pimage"]["size"] == 0) {
$uploadOk = 0;
$data=array("msg" => "profile image should not greater than 2 MB.");
}
//echo $uploadOk;exit;
if ($uploadOk==0) {
$flag=0;
$data[]=array("msg" => $data['msg']);
}else{
$moved =move_uploaded_file($tempFile, $targetFile);
if ($moved) {
$filename = $saveFile;
$data = array('ai_image' => $filename);
$this->db->where('accounts_id', $dataArr['user_id']);
$this->db->update('pt_operator_accounts', $data);
}else{
$flag=0;
$data[]=array("msg" => "Not uploaded because of error #".$_FILES["pimage"]["error"]);
}
// print_r($data);exit;
}
}
}
Here I need to write file into PT_USERS_IMAGES_UPLOAD path but before uploading into this path also the file is uploading into project's root path. Here I need to upload only in PT_USERS_IMAGES_UPLOAD path not in project's root path.
It is likely because of these lines:
imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
If you look at the documentation regarding this imagepng(), it will either output an image to the browser (with a proper header) or save the file to disk when you fill out the second parameter, in your case you have used the to parameter ($saveFile). So, once you save it there, you then save it again using the move_uploaded_file($tempFile, $targetFile); which is the one saving it to the proper location.
If you are trying to convert something to PNG, then just do the imagepng() line and remove the move_uploaded_file() line. Change $saveFile to T_USERS_IMAGES_UPLOAD and then you should only get one saved file. Either way, remove one of those methods for saving the file to disk.
I am trying to upload a file to two different locations. The lcoations being /2x/ adn /3x/. It uploads the file on 3x but doesn't on 2x and throws this error:
The file was not uploaded due to an unknown error
Here is what i am doing:
$photo = $request->file('photo');
if (isset($photo)) {
if ($photo != null || $photo != '') {
$imageSize = getimagesize($photo);
$resolution = $imageSize[0] . 'x' . $imageSize[1];
if ($resolution == '300x300' || $resolution == '450x450') {
if (!file_exists(base_path('uploads/custom_avatar'))) {
mkdir(base_path('uploads/custom_avatar'), 0777, true);
}
$resolution = "3x";
$uploadPath = base_path('uploads/custom_avatar/' . $resolution . '/');
$otherImageResolution = '2x';
$otherImagePath = base_path('uploads/custom_avatar/' . $otherImageResolution . '/');
//echo $otherImagePath;exit;
// saving image
$fileName = $child->id . '_' . time() . '.png';
$photo->move($uploadPath, $fileName);
$photo->move($otherImagePath, $fileName);
// creating records
$childImage = Images::addPhoto($child->id, $fileName, $resolution);
$otherImage = Images::addPhoto($child->id, $fileName, $otherImageResolution);
if ($childImage && $otherImage) {
$result = Child::createChildResponseData($child);
\Log::info('Child avatar added Successfully' . json_encode($childImage));
return response()->json([
'status' => $this->SUCCESS,
'response' => $result,
], $this->SUCCESS);
}
Any help?
Check your code if your file upload code is running two times.
I was facing the same issue & then I find that my file upload code is running two times.
after commenting one of them it's working fine.
You can try this:
$request->file('photo')->move($destination_path, $file_name);
Add DIRECTORY_SEPARATOR between path and filename if needed and
copy that file at new location
copy($destination_path.$file_name, $new_path.$new_file_name);
Check your code if your file upload code is running two times.
You can check this part of the code. Make sure you type it correctly and not repeat it twice.
// Original size upload file
$section_image_file->move($folder, $section_image_name);
I'm trying to upload files in php using the following function :
public function fileUpload($FILES){
$num_of_uploads = 1;
$max_file_size = 1048576; //can't be larger than 1 MB
$T = array ();
foreach($_FILES["file"]["error"] as $key=>$value){
if($_FILES["file"]["name"][$key] != ""){
if($value == UPLOAD_ERR_OK){
$v = array ();
$origfilename = $_FILES["file"]["name"][$key];
$filename = explode(".", $_FILES["file"]["name"][$key]);
$filenameext = $filename[count($filename) - 1];
$v['name'] = $filename[0];
$v['extension'] = $filename[1];
$v['type'] = $_FILES["file"]["type"][$key];
unset($filename[count($filename) - 1]);
$filename = implode(".", $filename);
$filename = "file__" . time() . "." . $filenameext;
if($_FILES["file"]["size"][$key] < $max_file_size){
$v['content'] = file_get_contents($_FILES["file"]["tmp_name"][$key]);
$T[] = $v;
}else{
throw new Exception($origfilename . " file size inaccepted!<br />");
}
}else{
throw new Exception($origfilename . " Error of upload <br />");
}
}
}
return $T;
}
This function works great with txt types, but when I'm testing pdf, or gif or jpg, it returns a damaged file.
As far as I know, file_get_contents() works well on text/html types.
However, for other file types you should parse their text content first to use it in further processing. Try opening any .pdf in Notepad to see it's text content.
For uploading purposes, use move_uploaded_file() in your cycle, like this:
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $filename);
Of course, without trying to get text content from uploaded file.
For downloading the file, you need to set headers. So, at the starting of function try setting any of below header for png or jpeg files:
//For png file
header("Content-Type: image/png");
//For jpeg file
header("Content-Type: image/jpeg");
I have a problem, I have view file, but how to save these uploads in to webroot/files. Im using CakePHP:
This is my uploadfile.ctp
echo $this->Form->create('YourModel', array('type' => 'file','enctype'=>'multipart/form-data'));
echo $this->Form->input('files.', array('type' => 'file', 'multiple'));
echo $this->Form->end('Submit');
I dont know where to start in Controller, I really need these files in to webroot/files, thankyou !
At the moment I have in Controller:
public function uploadFile() {
if ($this->request->is('UploadFile')) {
$tmp_name=$this->request->data['UploadFile']['image'];
$filename = time().$this->request->data['UploadFile']['image']['name'];
if (move_uploaded_file($tmp_name['tmp_name'],WWW_ROOT."/files".$filename)) {
} else {
$this->Session->setFlash('There was a problem uploading file. Please try again.','default',array('class'=>'alert alert-danger'));
}
}
}
UPDATE
Now I have updated view file and updated Controller, where I want to upload multiple files, but only one file going in to files folder.
View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
Controller File:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
and this Javascript:
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
How I can upload all 3 files in to webroot/files folder ?
try this code , this is a demo code and its is work on my server
<div class="col-sm-12">
<?php echo $this->Form->file('Feature.image.',array('class'=>'form-control','label'=>false,'div'=>false,'required','multiple'));?>
</div>
if ($this->request->is('post')) {
$data=$this->request->data['Feature']['image'];
foreach ($data as $key => $value) {
$this->request->data['Feature']['image'][$key]['name'];
$tmp_name=$this->request->data['Feature']['image'][$key];
$filename = time().$this->request->data['Feature']['image'][$key]['name'];
if (move_uploaded_file($tmp_name['tmp_name'],WWW_ROOT."/img/feature/".$filename)) {
$updatefile= $this->Feature->updateAll(
array('Feature.image' => "'$filename'"),
array('Feature.id' => $id,'Feature.userid'=>$this->Session->read('Auth.User.id'))
);
if($updatefile==1){
$file = new File(WWW_ROOT . 'img/feature/'.$featuredata['Feature']['image'], false, 0777);
if($file->delete()) {
$this->Session->setFlash('File uploaded successfuly uploaded.','default',array('class'=>'alert alert-success'),'success');
return $this->redirect(array('controller'=>'Users','action'=>'featureshow')) ;
}
}
} else {
$this->Session->setFlash('There was a problem uploading file. Please try again.','default',array('class'=>'alert alert-danger'));
}
}
}
No, of course you do not need a table.
I guess you are looking for something like this in your controller:
foreach($this->request->data['files'] as $file){
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'uploads/' . $uuid . '.jpg');
}
Use this:-
$uploadedFile = $this->request->params['form']['uploadCsv']['tmp_name'];
$dir = WWW_ROOT . 'files/';
if ( !is_dir( $dir ) ) {
mkdir($dir);
chmod( $dir , 777);
}
$fileName = 'file_' . date( 'Y_m_d_h_i_s', time() );
move_uploaded_file( $uploadedFile, $dir. $fileName . '.csv' );
This is a sample code which works on my server, and should work for you as well