I'm a beginner in jQuery. I really don't know how to do this but have the basic idea.
I'm using this jQuery uploader by Hayageek and I'm trying to move uploaded files to its permanent directory after form submits.
So, this is how it goes. The user first selects the file and the upload to TEMP directory starts and just stores an json array. But then the user accidentally adds a file that he never meant to and wants to remove that file (removing the array object). After correcting his mistake he then submits the form and the files get stored in a permanent directory.
This is what I have:
upload.php:
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
$ret[]= $fileName;
}
else //Multiple files, file[]
{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
$ret[]= $fileName;
}
}
echo json_encode($ret);
}
Delete file:
//This is the part where you unset the array object of a file.
index.php:
<script>
$(document).ready(function()
{
var settings = {
url: "upload.php",
dragDrop:true,
fileName: "myfile",
allowedTypes:"jpg,png,gif,doc,pdf,zip",
returnType:"json",
onSuccess:function(files,data,xhr)
{
// alert((data));
},
showDelete:true,
deleteCallback: function(data,pd)
{
for(var i=0;i<data.length;i++)
{
$.post("delete.php",{op:"delete",name:data[i]},
function(resp, textStatus, jqXHR)
{
//Show Message
$("#status").append("<div>File Deleted</div>");
});
}
pd.statusbar.hide(); //You choice to hide/not.
}
}
var uploadObj = $("#mulitplefileuploader").uploadFile(settings);
});
</script>
<form action="upload.php" name="upload_form" enctype="multipart/form-data" method="POST">
<div>
<label>Message</label>
<textarea name="description" style="min-height:200px;" value="<?php echo $mess; ?>"></textarea>
<div id="mulitplefileuploader">Upload</div>
<div id="status"></div>
<input type="submit" name="submit" value="Create Project">
</div>
</form>
<?php if(isset($_POST['submit'])){
$tmp_file=$_FILES['myfile']['tmp_name'];
$dir="upload/";
$file_name=$_FILES['myfile']['name'];
if(move_uploaded_file($tmp_file,$dir . $file_name)){
echo "success";
}else{echo "failure";}
}
?>
You can refer some of plugins available online.
https://blueimp.github.io/jQuery-File-Upload/basic-plus.html this is one of them...
Related
I have experience doing this with single file uploads using <input type="file">. However, I am having trouble doing uploading more than one at a time.
For example, I'd like to select a series of images and then upload them to the server, all at once.
It would be great to use a single file input control, if possible.
Does anyone know how to accomplish this?
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:
<form enctype="multipart/form-data" action="post_upload.php" method="POST">
Then the key to success;
<input type="file" name="file[]" multiple />
do NOT forget those brackets!
In the post_upload.php try the following:
<?php print_r($_FILES['file']['tmp_name']); ?>
Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:
$_FILES['file']['tmp_name'][0]
You can use php count() to count the number of files that was selected. Goodluck widdit!
Full solution in Firefox 5:
<html>
<head>
</head>
<body>
<form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
<input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input>
</form>
<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>";
$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {
echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
$ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
$result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);
if (strlen($ext) > 0){
echo "Uploaded ". $fPath ." succefully. <br>";
}
}
echo "Upload complete.<br>";
?>
</body>
</html>
in the first you should make form like this :
<form method="post" enctype="multipart/form-data" >
<input type="file" name="file[]" multiple id="file"/>
<input type="submit" name="ok" />
</form>
that is right . now add this code under your form code or on the any page you like
<?php
if(isset($_POST['ok']))
foreach ($_FILES['file']['name'] as $filename) {
echo $filename.'<br/>';
}
?>
it's easy... finish
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.
If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.
Update:
There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.
http://swfupload.org/
If you use multiple input fields you can set name="file[]" (or any other name). That will put them in an array when you upload them ($_FILES['file'] = array ({file_array},{file_array]..))
partial answer: pear HTTP_UPLOAD can be usefull
http://pear.php.net/manual/en/package.http.http-upload.examples.php
there is a full example for multiple files
i have created a php function which is used to upload multiple images,
this function can upload multiple images in specific folder as well it can saves the records into the database
in the following code
$arrayimage is the array of images which is sent through form
note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.
$dir is the directory in which you want to save the image
$fields is the name of the field which you want to store in the database
database field must be in array formate
example
if you have database imagestore and fields name like id,name,address then you need to post data like
$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);
and then pass that field into function $fields
$table is the name of the table in which you want to store the data..
function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
//extracting extension of uploaded file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $arrayimage["name"]);
$extension = end($temp);
//validating image
if ((($arrayimage["type"] == "image/gif")
|| ($arrayimage["type"] == "image/jpeg")
|| ($arrayimage["type"] == "image/jpg")
|| ($arrayimage["type"] == "image/pjpeg")
|| ($arrayimage["type"] == "image/x-png")
|| ($arrayimage["type"] == "image/png"))
//check image size
&& ($arrayimage["size"] < 20000000)
//check iamge extension in above created extension array
&& in_array($extension, $allowedExts))
{
if ($arrayimage["error"] > 0)
{
echo "Error: " . $arrayimage["error"] . "<br>";
}
else
{
echo "Upload: " . $arrayimage["name"] . "<br>";
echo "Type: " . $arrayimage["type"] . "<br>";
echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
echo "Stored in: ".$arrayimage['tmp_name']."<br>";
//check if file is exist in folder of not
if (file_exists($dir."/".$arrayimage["name"]))
{
echo $arrayimage['name'] . " already exists. ";
}
else
{
//extracting database fields and value
foreach($fields as $key=>$val)
{
$f[]=$key;
$v[]=$val;
$fi=implode(",",$f);
$value=implode("','",$v);
}
//dynamic sql for inserting data into any table
$sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
//echo $sql;
$imginsquery=mysql_query($sql);
move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
echo "<br> Stored in: " .$dir ."/ Folder <br>";
}
}
}
//if file not match with extension
else
{
echo "Invalid file";
}
}
//function imageUpload ends here
}
//imageFunctions class ends here
you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code
I'm trying to create a specific module to upload files.
I'm using this code:
Client side:
<?php
// No direct access
defined('_JEXEC') or die; $resposta =""; ?>
<form name="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="submit" name="submit_file" value="submit_file"/>
<input type="text" name="resposta" value=<?php echo $resposta; ?> />
</form>
My module:
<?php
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
//trigger the event
// Instantiate global document object
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';
$resposta = ModuploadfileHelper::getuploadfile($params);
require JModuleHelper::getLayoutPath('mod_upload_file');
?>
My helper:
<?php
class ModuploadfileHelper {
public static function getuploadfile($params) {
/*
* File upload example
*/
//Retrieve file details from uploaded file, sent from upload form
$file = JFactory::getApplication()->input->get('file_upload');
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
if(!JFolder::exists($dest))
{
$mode = 0755;
JFolder::create($dest, $mode);
}
$resposta = null;
//First check if the file has the right extension, we need jpg only
if (strtolower(JFile::getExt($filename)) == 'jpg')
{
// TODO: Add security checks
if (JFile::upload($src, $dest))
{
$resposta = "Sucesso ao arquivar a imagem";
}
else
{
$resposta = "Insucesso ao arquivar a imagem";
}
}
else
{
$resposta = "O ficheiro não é uma imagem";
}
return $resposta;
}
}
?>
First question: Does something like this work?
Second question: How to perform a trigger for the module to work?
Thirteenth question: How to pass the module to ajax?
I have something like this:
Module code:
<?php
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
// Instantiate global document object
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';
$resposta = ModuploadfileHelper::getuploadfile($params);
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('click', 'input[type=submit]', function () {
formdata = new FormData();
var file = this.files[0];
formdata.append("image", file);
$.ajax({
type : 'POST',
data : request,
success: function (response) {
$('.search-results').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
require JModuleHelper::getLayoutPath('mod_upload_file');
?>
Help me please.
It is possible, what you need to do, is to use the Joomla ajax interface.
See the documentation here: https://docs.joomla.org/Using_Joomla_Ajax_Interface
There is a full example of a module implementing this, that you can easily modify to adapt to file upload:
https://github.com/Joomla-Ajax-Interface/Ajax-Session-Module
I can't download file.I am trying to download file from server through Ajax. I got success response in Ajax data and also file in response but file was not download what i do and how to fix this issue. The file reads successfully and also sever path get proper. Please help me.
This one is java script when i call function and get response throw ajax
<script type="text/javascript">
function push_file(files)
{
$.ajax
({
type: "post",
url: "<?php echo base_url(); ?>Appointment/download_files/",
data: "files=" + files,
success: function(data)
{
alert('ok' + data);
}
});
}
</script>
PHP code and here i want to download file here and
foreach($results as $row){
$r_id = $row->id;
<td><h5><a onclick="push_file(<?php echo $r_id;?>)"> Download </a></hs><t>
}
Controller
Ajax and PHP perform perfectly and read file but its not download
public function download_files() {
//$this->load->view ( 'ajax/download' );
if($_POST)
{
$base = base_url();
$id = $_POST['files'];
$query = $this->db->query("select userfile from patient_report_file where id='".$id."'");
$result = $query ->row();
$name = $result->userfile;
echo $path = $base."Admin/uploads/patient_report/".$name;
force_download($path, NULL);
}
}
How can I download the file.
You try to download a file through ajax which is impossible (at least the way you did it)
Now you have two options
Option #1 - leave the JS behind (why do you even need JS here - an
alert after downloading is useless imho)
your view should look like
foreach($results as $row)
{
echo '<td><h5> Download </h5></td>';
}
and your controller
public function download_files($id)
{
//$this->load->view ( 'ajax/download' );
$base = base_url();
$id = $_POST['files'];
$query = $this->db->query("select userfile from patient_report_file where id='".$id."'");
$result = $query ->row();
$path = $base."Admin/uploads/patient_report/".$result->userfile;
force_download($path, NULL);
}
Option #2 - is a bit more tricky, because it needs some adaption, i'm not gonna write that code for you, but instead i give you some links to study
Download a file by jQuery.Ajax
https://github.com/eligrey/FileSaver.js/
download file using an ajax request
Overall i'm not judging your code but you did a pretty bad job in order to use CI properly ;)
If you want using method POST that this is my solution:
crsf enable:
<script>
function push_file(files)
{
$('<form action="<?php echo site_url('admin/others/test');?>" method="post"><input type="hidden" name="files" value="'+files+'"><input type="hidden" name="csrf_token_name" value="<?php echo $this->input->cookie('csrf_cookie_name');?>"></form>').submit();
}
</script>
crsf disable:
<script>
function push_file(files)
{
$('<form action="<?php echo site_url('admin/others/test');?>" method="post"><input type="hidden" name="files" value="'+files+'"></form>').submit();
}
</script>
you must change path controller.
Hi i'm currently developing a php page which has an file upload feature. my form sends over 2 hidden values which is an order id and sender id and the file. I have to use ajax as i can't make it refresh after upload. The file upload has to be in my upload/files folder and i need to store the order id , sender id and filename in mysql.My ajax is getting the order id and sender id when i serialize but not the file. i tried seraching on this site for solutions and came acrross FormData object way to no success and also few other methods. the error in my console is always undefined sender_id, file order_id. It doesnt get the values from the html form. Thanks for helping.
MY php, html form
<form method="POST " id="form1" name="form1" enctype='multipart/form-data' >
<input type="hidden" name="sender_id" value="<?php echo $_SESSION['user_session']?>">
<input type="hidden" name="order_id" value="<?php echo $_GET['oid']?>">
<?php //echo var_dump($sellerinfo);?>
<div>
<div>
<textarea name="comments" placeholder="Leave Comments Here..." style="width:800px; height:100px;"></textarea>
<div class="row">
<input type="file" id="file" name="fileupload">
<input type="reset" value="Reset">
<a type="file" href="" class="button" id="fileupload" name="fileupload"> UPLOAD FILE </a>
<br>
<a id="comment" href="" class="button">Post</a>
<input type="reset" value="Reset">
</form>
File.js (ajax file)
$("#fileupload").click(function(e){
alert("inside ajax");
var formData = $("#form1").serialize()
alert(formData);
var formData = new FormData();
var file_data = $('#file').prop('files')[0];
formData.append('file', file_data);
alert(formData);
$.ajax({
url: '../modules/Comment/fileupload.php',
type: 'POST',
dataType:"json",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
error: function (result) {
console.log(result);
alert('ERROR RUNNING INSERTSCRIPT');
},
success: function (result) {
alert(result)
if (result['result'] == true) {
alert("success");
order_id = document.form1.order_id.value;
$('#comment_logs').load("../modules/comment/file_logs.php?",{oid:order_id} );
}
else if (result['result'] == false) {
alert('ERROR');
}
},
});
});
My php script that is supposed to upload and insert data inside database.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require('commentclass.php');
$connect = new connect(); // new connect class OBJECT
$conn = $connect->get_connection(); // getting Connection from Connect Object
$sender_id=$_POST['sender_id'];
$order_id=$_POST['order_id'];
$Filename=basename( $_FILES['Filename']['name']);
define ('SITE_ROOT', realpath(dirname(__FILE__)));
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], '../../uploads/files/' . $_FILES['file']['name'])) ;
{
echo "The file " . basename($_FILES['Filename']['name']) . " has been uploaded, and your information has been added to the directory";
$sql = "INSERT INTO files(order_id,send_by,file_name) VALUES ('" . $order_id . "','" . $sender_id . "','" . $Filename . "')";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result) {
$data['result'] = true;
echo json_encode($data);
}
else
{
$data['result'] = true;
echo json_encode($data);
}
}
}
?>
Sorry for the long post, hope someone can help . Thanks in advance
I have a php file and I have created 2 buttons get and set in the file.
I want to access Get.php file when I click get
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
and Set.php file when I select set button.
<?php
$file = "xxx.json";
include 'Set.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
My file visual.php file contents are:
<!DOCTYPE html>
<meta charset="utf-8">
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
<style>
right {
display:table-cell;
vertical-align:top;
width:300px;
padding:0 5px;
}
<?php
$color=include('Color.php');
echo $color;
?>
</style>
<body>
<div id=tt>
<button type="submit" onclick="get()"> <b>get</b></button>
<button type="submit" onclick="set()"> <b>set</b></button>
</div>
<div id=graph>
<script src="ll.js"></script>
<script src="visual.js"></script>
<script type="text/javascript">
window.onload = function(){
}
<?php
$link=include('Link.php');
echo $link;
?>
</script>
</div>
<body>
I am not sure how can I get the contents for Get.php file and Set.php file. I know that I can call ajax calls. But in that case only I can get the contents of the Get.php or Set.php files.
But how can I also make other data shown below execute in sequential order.
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
I am new to php. Thanks for all your help.
Bes way, is using standard html methods: name-value for form elements
<body>
<form method="GET">
<button type="submit" name="event" value="get"> <b>get</b></button>
<button type="submit" name="event" value="set"> <b>set</b></button>
</form>
<body>
And the php code:
$file = "xxx.json";
switch ($_GET['event'])
{
case 'get': include 'Get.php'; break;
case 'set': include 'Set.php'; break;
}
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
Dmitriy's answer is pretty easy, and clean looking. I like.
Ive made a little longer example, utilizing a class aswell, and commented it throughoutly for you to perhaps learn a little or two. Hope it helps!
<?php
class HandleFile {
protected $file;
//The construct is called, when the object is created. We request the file here.
public function __construct($file = null) {
//Lets check if the file variable is set or not.
if( !is_null($file) ) {
//Lets check if the file actually exists
if( file_exists($file) ) {
//If the file exists, set the class variable.
$this->file = $file;
} else {
//If the file does not exist. Throw an exception
throw new Exception("Construct:: The file " . $file . ", does not exist.");
}
} else {
//If the file variable is not set, throw an exception.
throw new Exception("Construct:: No file specified.");
}
}
//This function will do our actual logic.
public function doAction($fileToInclude) {
//First, check if the file to include exists.
if( file_exists($fileToInclude) ) {
//Include it
include($fileToInclude);
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($this->file,$output);
} else {
//If it does not exist. Throw exception.
throw new Exception("doAction:: File " . $fileToInclude . ", does not exist.");
}
}
}
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler = new HandleFile("xxx.json");
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
//Define a helper variable
$action = null;
//If the GET parameter "get" is set, do a get action
if( isset( $_GET['get'] ) ) {
$action = "Get.php";
//If the GET parameter "post" is set, do a post action.
} elseif( isset( $_GET['post'] ) ) {
$action = "Post.php";
}
//If our helper variable has changed, there must be an action to do.
if( !is_null($action) ) {
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler->doAction($action);
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
}
?>
<body>
<form action="" method="GET">
<button type="submit" name="get" value="yes"> <b>get</b></button>
<button type="submit" name="post" value="yes"> <b>set</b></button>
</form>
<body>
You're calling a function which isn't set...
why don't you use $_POST
to with 2 different forms
1 hidden input contains the id type
if the type is get then include the get
if the type is set then include the set
this is just an example tho'