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
Related
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
I want to use Dropzone.js to store files to the server and also store the file link to the MySQL database. But I can't find a way to get it return the link of the uploaded files.
How can I do with this?
Here's the code:
<section id="home">
<form action="handler.php?user_id=<?php echo $user->data()->id; ?>" class="dropzone" id="my-dropzone">
<div class="fallback">
<input name="file" type="file" multiple id="up" />
</div>
</form>
</section>
<script>
Dropzone.options.myDropzone = {
addRemoveLinks: true,
init: function() {
thisDropzone = this;
$.get('handler.php?action=show', function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.link};
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/<?php echo $user->data()->id; ?>/"+value.name);
});
});
thisDropzone.on('removedfile', function(file){
$.get('handler.php?action=remove&name='+file.name+'&user_id=<?php echo $user->data()->id; ?>');
});
}
}
</script>
handler.php:
<?php
define('DS',DIRECTORY_SEPARATOR);
define('DES','uploads');
$action = "upload";
if (isset($_GET['action'])) {
$action = $_GET['action'];
}
//routing for different tasks
switch($action) {
case 'upload':
if (!empty($_FILES)) {
storeFile($_FILES, $_GET['user_id']);
}
break;
case 'remove':
$filename = $_GET['name'];
removeFile($filename, $_GET['user_id']);
break;
case 'show':
showFiles();
break;
}
function storeFile($file, $user_id) {
$tempFile = $file['file']['tmp_name'];
//file extensions allowed
$allowedExt = array('gif', 'jpg');
//file size allowed in kb
$allowedMaxSize = 10240;
//file extension validation
if ( count($allowedExt) >0 ) {
$fileExt = pathinfo($file['file']['name'],PATHINFO_EXTENSION);
if ( !in_array( $fileExt, $allowedExt ) ) {
header("HTTP/1.0 500 Internal Server Error");
echo 'Invalid file extension';
exit();
}
}
//file size validation
if ( (filesize($tempFile)/1024)> $allowedMaxSize ) {
header("HTTP/1.0 500 Internal Server Error");
echo 'File exceeds maximum allowed size';
exit();
}
//move file to server
$targetPath = dirname( __FILE__ ) . DS . DES . DS . $user_id;
if (!is_dir($targetPath)) {
mkdir($targetPath);
}
$targetFile = $targetPath . DS . $file['file']['name'];
if ( !move_uploaded_file($tempFile,$targetFile) ) {
header("HTTP/1.0 500 Internal Server Error Not Found");
echo 'Unknown server error';
exit();
}
}
function showFiles() {
$result = array();
$files = scandir(DES);
if ( false!==$files ) {
foreach ( $files as $file ) {
//ignore current and parent folder indicator
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize(DES.DS.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
function removeFile($fileName, $user_id) {
$targetPath = dirname( __FILE__ ) . DS . DES . DS . $user_id . DS;
$targetFile = $targetPath . $fileName;
//remove only when file exists
if (file_exists($targetFile)) {
unlink($targetFile);
}
}
?>
Not sure if you have resolved your issue, but I use this example and all works well
Dropzonejs Example
index.php
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form action="upload.php" class="dropzone">
</form>
<script src="js/dropzone.min.js"></script>
</body>
</html>
upload.php
<?php
//require 'yourconnectionfile.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "./uploads";
if (!empty($_FILES)) {
$fileupload = basename( $_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
//Your Upload SQL goes here
//$uploadsql = "INSERT INTO uploads (Filename, description, Type, Size)
// VALUES ('$fileupload', 'test uploads', '$fileType', '$fileSize')";
//mysql_query($uploadsql);
}
?>
Use the example above to get the css & the js code along with a couple of images.
I used the Codeigniter's Upload Class to upload images to a folder in the project. In the database I only store the the url generated after upload the image, so when I want to delete a row in the db I also need to delete the image. How can I do it in codeigniter?
I will be grateful for your answers.
You can delete all the files in a given path, for example in the uploads folder, using this deleteFiles() function which could be in one of your models:
$path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
function deleteFiles($path){
$files = glob($path.'*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
//echo $file.'file deleted';
}
}
delete_row_from_db(); unlink('/path/to/file');
/path/to/file must be real path.
For eg :
if your folder is like this htp://example.com/uploads
$path = realpath(APPPATH . '../uploads');
APPPATH = path to the application folder.
Its working...
if(isset($_FILES['image']) && $_FILES['image']['name'] != '')
{
$config['upload_path'] = './upload/image';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['file_name'] = base64_encode("" . mt_rand());
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg', 'We had an error trying. Unable upload image');
}
else
{
$image_data = $this->upload->data();
#unlink("./upload/image/".$_POST['prev_image']);
$testData['image'] = $image_data['file_name'];
}
}
$m_img_real= $_SERVER['DOCUMENT_ROOT'].'/images/shop/real_images/'.$data['settings']->shop_now;
$m_img_thumbs = $_SERVER['DOCUMENT_ROOT'].'/images/shop/thumbs/'.$data['settings']->shop_now;
if (file_exists($m_img_real) && file_exists($m_img_thumbs))
{
unlink($m_img_real);
unlink($m_img_thumbs);
}
View:
<input type="file" name="new_file" data-required="1" class="" />
<input type="hidden" name="old_file" value="echo your old file name"/>
<input type="submit" name="submit"/>
Controller:
function edit_image() {
if(isset($_FILES['new_file']['name']) && $_FILES['new_file']['name'] != '') {
move_uploaded_file($_FILES['new_file']['tmp_name'],'./public_html/banner/'.$_FILES['new_file']['name']);
$upload = $_FILES['new_file']['name'];
$name = $post['old_file'];
#unlink("./public_html/banner/".$name);
}
else {
$upload = $post['old_file'];
}
}
Try using delete_files('path') function offered by CI framework itself:
https://ellislab.com/codeigniter/user-guide/helpers/file_helper.html
$image_data = $this->upload->data();
unlink($image_data['full_path']);
This line $this->upload->data() will return many information about uploaded file. You can print information and work accordingly.
I have created the script of downloading an facebook album in php. When I will click on download button, script is fetching all photos in that album behind the scene and zip them inside a folder. I want to start a “progress bar” as soon as user-click download button as download process may take time.
Following is index.php
if ($album['count'] != "0 photos")
{
echo "";
}
Here I am passing album id to the download.php
and following is the code for download.php where I am downloading images into the downloads folder, creating the zip file of all that images and downloading that zip file.
<?php
require 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
));
//GETTING THE ID HERE FROM INDEX.PHP FILE
$albumid = $_GET['id'];
$photos = $facebook->api("/{$albumid}/photos?limit=50");
$file_name = rand(1, 99999) . "_image.zip";
$albumArr = array();
foreach ($photos['data'] as $photo) {
$albumArr[] = $photo['source'];
}
create_zip($albumArr, $file_name);
function create_zip($files, $file_name, $overwrite = false) {
$i = 0;
$imgFiles = array();
foreach ($files as $imglink) {
$img = #file_get_contents($imglink);
$destination_path = 'downloads/' . time() . "Image_" . $i . '.jpg';
#file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
$i++;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
$size1 = 0;
foreach ($valid_files as $file) {
$size1+= filesize($file);
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$zip->close();
$allimages = glob('downloads/*.jpg');
foreach ($allimages as $img) { // iterate images
if (is_file($img)) {
unlink($img); // delete images
}
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['HTTP_HOST'] . '/';
$path = $filepath . $filename;
if (file_exists($filename)) {
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($filename);
unlink($filename);
}
} else {
return false;
}
}
?>
I want to start a “progress bar” as soon as user-click download button as download process may take time.
How can I do this? Thanks
Something like this? PLease tell me if I didn't understand your question
HTML:
<img id="loadingImage" src="pathToImage" alt="" style="display:none" />
//pathToImage is the path to where your image is located
jQuery:
$('#YourButtonID').click(function(){
$('#loadingImage').css('display','block');
//call your download page
return false;
});
After your download and redirect are finished, call this method to hide the progressbar
$('#loadingImage').css('display','none');
You can do this by using ajax.
$(document).ready(function()
{
$("#download_button").click(function() {
document.getElementById('progressbar').style.display='';
//call your download page.
});
});
I am trying to upload multiple images. I am using Codeigniter and I know there is a built in file upload class but I am just experimenting with my custom made image upload library. I have provided the code below.
The problem I am facing with the following code is it is just uploading only one (the one that is selected at last in the form) image.
Could you please kindly tell me where I am doing wrong?
My Controller:
function img_upload(){
$this->load->library('image_upload');
$image1= $this->image_upload->upload_image('imagefile1');
$image2= $this->image_upload->upload_image('imagefile2');
$image3= $this->image_upload->upload_image('imagefile3');
echo $image1 ."<br>"; echo $image2;
}
application/libraries/image_upload.php (Custom made library)
function upload_image($image_info){
$image=$_FILES[$image_info]['name'];
$filename = stripslashes($image);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
$image_name=time().'.'.$extension;
$newname="support/images/products/".$image_name;
$uploaded = move_uploaded_file($_FILES[$image_info]['tmp_name'], $newname);
if($uploaded) {return $image_name; } else {return FALSE;}
}
My Form
<form id="myForm" enctype="multipart/form-data"
action="<?php echo base_url();?>add/img_upload" method="post" name="myForm">
<input type="file" name="imagefile1" size="20" /><br>
<input type="file" name="imagefile2" size="20" /><br>
<input type="file" name="imagefile3" size="20" /><br>
<br /><br />
<input type="submit" value="upload" />
</form>
you can create some kind of rollback functionality and use CI native lib . it's little extra work for the server but it's less/clean/easyTOdebug code and it works .
function do_upload()
{
1 - configuration
$config['upload_path'] = './uploads/';
// other configurations
$this->load->library('upload', $config);
$error = array('stat'=>0 , 'reason'=>'' ;
2- uploading
if ( ! $this->upload->do_upload('file_1'))
{
$error['stat'] = 1 ;
$error['reason'] = $this->upload->display_errors() ;
}
else
{ $uploaded_array[] = $uploaded_file_name ; }
// you may need to clean and re initialize library before new upload
if ( ! $this->upload->do_upload('file_2'))
{
$error['stat'] = 1 ;
$error['reason'] = $this->upload->display_errors() ;
}
else
{ $uploaded_array[] = $uploaded_file_name ; }
3 - checking for errors and rollback at the end
if($error['stat'] == 1 )
{
$upload_path = './upload/';
if(!empty($uploaded_array))
{
foreach( $uploaded_array as $uploaded )
{
$file = $upload_path.$uploaded;
if(is_file($file))
unlink($file);
}
}
echo 'there was a problem : '.$error['reason'];
}
else
{
echo 'success';
}
}
I have found the solution to my problem, and thought it could help someone if I share.
The problem was in the image_upload.php file (custom made library), specifically in this line:
$image_name=time().'.'.$extension; //
time() was perhaps overwriting the files. So I replaced my previous code with the following:
function upload_image($image_info){
$image=$_FILES[$image_info]['name'];
$filename = stripslashes($image);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
$image_name=$this->get_random_number().'.'.$extension;
$newname="support/images/products/".$image_name;
$uploaded = move_uploaded_file($_FILES[$image_info]['tmp_name'], $newname);
if($uploaded) {return $image_name; } else {return FALSE;}
}
function get_random_number(){
$today = date('YmdHi');
$startDate = date('YmdHi', strtotime('-10 days'));
$range = $today - $startDate;
$rand1 = rand(0, $range);
$rand2 = rand(0, 600000);
return $value=($rand1+$rand2);
}