Adding and displaying multiple images [duplicate] - javascript

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

Related

PHP File upload not working after completing all the steps. (I think)

Here's my background:
I'm using Amazon EC2 Linux Instance running Apache and LAMP.
I'm trying to make a PHP image upload.
I got the code from W3Schools.
I have tried signing in as Superuser (su) and changing the permissions on the upload folder (/var/www/html/photo/backend/images/uploads) to chmod 755.
I have tried running print_r($_FILES); and get Array ( ).
I've changed these things in php.ini:
set file_uploads to on
set max_execution_time to 300 (seconds)
set max_file_size to 100 (MB)
I've tried and Googled everything I can think of and I still can't figure out why my image doesn't upload. I'm sorry if this is broad, but I really don't know what the problem is.
Issue:
Image doesn't upload (no idea why, I think I've followed all the steps, see above)
Here's my code:
<?php
$target_dir = "/backend/images/uploads";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
print_r($_FILES);
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="/backend/images/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Thanks for reading, and if anything doesn't make sense, please comment!
add / after uploads
change
$target_dir = "/backend/images/uploads";
to below code
$target_dir = "/backend/images/uploads/";

passing array of string from php to html

I want to tranform a php array of string into html. My php and html code are in the same page.
I have $myvar that hold my array of string. I pass $myvar with POST and insert it to $ba.
My code needs to print on html page 3 line (in while loop).
But when I pass the $be, it writes me error message: "Notice: Undefined index: myvar" (in php code)
What do I need to repair so that my code prints to my screen all the 3 lines that I get from php?
my code:(php)
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("", $myvar);
my html code:
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p> <?php echo $ba ?> </p>
Simply echo the mysql query on a function and call it on HTML as follows:
UPDATE: 3rd column will be an image wich route are stored on database, and 4th col will be an image eich only the name was stored on database (because we know the full route) as example:
<?php
function printOnHtml(){
include ("connection.php");
$sql = "SELECT * FROM foo;"
if ($result = connection()->query($sql)){
$rs = $result->fetch_array(MYSQLI_NUM);
while ($rs[0] != ''){
echo "first column: ".$rs[0]." second column: ".$rs[1]." image with full route on database: <img src='".$rs[2]."' alt=''> <br> if only the img name is stored cuz we know the route: <img src='img_route/".$rs[3]."' alt=''>";
$rs = $result->fetch_array(MYSQLI_NUM);
}
}
}
Then on HTML
<html>
blablabla
<body>
blablabla
<?php
printOnHtml();
?>
blablabla
</body>
</html>
Note that it have to be a .php file to call the php function (for example index.php)
I paste the connection php script i use in order if you need it:
<?php
function connection(){
if($mysqli = new MySQLi("localhost","user","password","database_name")) echo "OK"; else echo "KO";
mysqli_set_charset($mysqli, "utf8");
return $mysqli;
}
?>
i did it with mysqli fetch array, but you can do the same using fetch assoc if you want.
UPDATE2: If you stubborness makes you follow using a txt to store data (wich, if increase will fail when you get a some thousands line txt), modify this on your code:
$myvar='';
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
if(isset($myvar)){
$myvar=fgets($handle);
}
$counter++;
}
}
}
and i'm supposing that you declared $dir, $file and other vars properly.
You NEVER have to use vars without declaring it (as NULL at least). You only can do this if you ensured 100% that this var will get a value at this point.
You have to convert the array to string in a correct way using implode and <br> as a separator
Then just print it using php tags (as you are using both at the same page ) you can access the variable direct and print it using <?= $ba ?> or <?php echo $ba ; ?>
Code will be :
<?php
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("<br>", $myvar);
?>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p id="deatiles"> <?= $ba ?> </p>

Multiple upload using jQuery and PHP

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...

How to show images onto browser? it's giving me errors

i've successfully uploaded my image into folder and successfully saved my path into database now as i tried to show pic into browser it's showing error:
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 6
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 7
File name not found in database
here is my code for form:
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "photo";
$username_connect= "root";
$password_connect= "Bhawanku";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
<html>
<body>
<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and here is my code for showing pics:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","photo");
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
In the second script, you're connecting as mysqli but then using mysql_query, mysql_num_rows and mysql_fetch_array. MySQLi and MySQL aren't interchangeable.
$result = mysqli_query($query_image, $con);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
You should consider changing the first script to MySQLi too, and use prepared statements instead of concatenating variables into the query.
In first row you use mysqli extension, but in all other - mysql.
Try to change:
<?php
$con=mysql_connect("localhost","root","Bhawanku");
mysql_select_db("photo", $con);
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>

Angularjs - File upload with php

I have spent days looking for a fairly simple integration of angularjs file upload method that includes a basic php server side script..
I need a simple form one field and file upload upload.
All examples I find are either heavily relying of jQuery or if they seem like something I could use their "examples" are completely unclear and messy.
These two examples (if I could figure out how to incorporate with PHP) would solve my puzzle..
Example 5 on this page
http://ng-upload.eu01.aws.af.cm/
And the example on this page is one I really like a lot..
http://angular-file-upload.appspot.com/
Could someone bring more light into this for me.. I would really like to see a one input filed and one file upload with as simple as possible angular and php code if such thing exists somewhere.
I would be happy to implement this http://twilson63.github.io/ngUpload/ or http://angular-file-upload.appspot.com/
If this is my PHP
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>
and this my basic html
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" name="fname" />
<input type="file" name="image" />
<input type="submit"/>
</form>
How could I approach this (cleanly)? What should my controller and adjusted html look like?
If you use ng-file-upload
You can do most of those pre-validation on the client side like checking the file size or type with ngf-max-size or ngf-pattern directives.
Upload.upload() will send a POST multipart/form-data request to the server so $_FILES['file'] should contain the uploaded file.
HTML
<div ng-controller="MyCtrl">
<input type="text" name="username" ng-model="username"/>
<input type="file" ngf-select="onFileSelect($file)" ngf-pattern="'image/*'" ngf-max-size="2M">
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function(file) {
if (!file) return;
Upload.upload({
url: '/upload.php',
data: {file: file, username: $scope.username}
}).then(function(resp) {
// file is uploaded successfully
console.log(resp.data);
});
};
}];
upload.php
$fname = $_POST["fname"];
if(isset($_FILES['image'])){
//The error validation could be done on the javascript client side.
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
?>
I was also battling with $files being undefined - I'll take a wild guess that you are writing the html code from php and haven't escaped the $ in $files. That was my problem anyway - should be \$files.
Dan

Categories