I want to upload different images from different folders in a single file upload form submit.
When I click the upload button for the second time before clicking the submit button, file input field get replace with the latest selections.
Is it possible to append the selections till the submit is clicked.
My JS code displays all the selected file. But submits only the last selections
Here is my HTML
<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
<input type='file' name='file1[]' id="upload-image" multiple />
<input type='hidden' name='file2' value="aaaaaaaa" />
<div id="upload-img">
<output id="list"></output>
</div>
<br/>
<button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>
Here is my JS
var allImages = [];
if (window.FileReader) {
document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
};
})(f);
reader.readAsDataURL(f);
}
var formData = $('form').serializeArray();
console.log(formData);
$.ajax({
type:'POST',
url: 'temp.php',
data:formData,
success:function(data){
//code here
},
error: function(data){
//code here
}
});
console.log(folder);
$('#upload-img').addClass('image-div');
}
And my PHP is just a var_dump for the moment
if (isset($_POST['submit'])) {
var_dump($_FILES['file1']);
var_dump($_POST['file2']);
}
You can try this:
Select file using browse field
call a method (setImage()) on onchange of this browse field
and in setImage():
function setImage(){
// Get the src value of browse field
// Create a new hidden browse field with src value of above browse
// field
// And set blank value of src of first one browse field
}
The idea is you select an image n times, the above method will create n hidden browse field in your html.
For example: If you select three images, then there will be four browse fields.
1 Shown to you
Other three are hidden
Now press submit and in server side you will get 4 file fields one with empty file and other three with files.
Ignore empty one and upload other three images.
With the hint given by Rahul I was able to make it work.
Here is the answer
JS File
var uploadImage = 0;
$( document ).ready(function() {
uploadImage = Math.floor(Date.now() / 1000);
});
if (window.FileReader) {
document.getElementById('upload-image').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
document.getElementById('list').innerHTML = document.getElementById('list').innerHTML + ['<img src="', e.target.result,'" title="', f.name, '" width="150" class="image-gap" />'].join('');
$('<input>').attr({
type: 'hidden',
id: uploadImage++,
name: uploadImage++,
value: e.target.result
}).appendTo('form');
console.log(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
$('#upload-img').addClass('image-div');
}
PHP Code
if (isset($_POST['submit'])) {
define('UPLOAD_DIR', 'images/');
$patterns = array('/data:image\//', '/;base64/');
foreach ($_POST as $key => $value) {
if (preg_match('/^(0|[1-9][0-9]*)$/', $key)) {
$imageData = explode(',', $value, 2);
$type = preg_replace($patterns, '', $imageData[0]);;
if (count($imageData) > 1) {
$img = str_replace($imageData[0].',', '', $value);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.'.$type;
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
}
}
}
}
HTML Code
<form name="status-form" id="status-form" method="post" enctype="multipart/form-data">
<input type='file' name='file1[]' id="upload-image" multiple />
<div id="upload-img">
<output id="list"></output>
</div>
<br/>
<button type="submit" name="submit" class="btn btn-info" id="status-btn">Send It!</button>
</form>
Related
I know you think this as a silly question. But I am not able to get it done. I am using dropbox chooser to upload the images form user's dropbox account. Once they upload it, I am able to save it in the database, but I am not able to save it in the uploads folder. Following is my code:
Index.php
<form class="form" method="post" enctype="multipart/form-data" >
<div id="dropbox-container"></div>
<input id="dropbox_image" name="image" type="hidden" />
<button type="submit" class="button">Save</button>
</form>
<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="wgiv8kvzvq57mlw"></script>
<script type="text/javascript">
options = {
success: function(files) {
files.forEach(function(file) {
add_img_to_list(file);
document.getElementById('dropbox_image').value = file['name'];
});
},
cancel: function() {
//optional
},
linkType: "preview", // "preview" or "direct"
multiselect: true, // true or false
extensions: ['.png', '.jpg'],
};
var button = Dropbox.createChooseButton(options);
document.getElementById("dropbox-container").appendChild(button);
function add_img_to_list(file) {
var li = document.createElement('li');
var a = document.createElement('a');
a.href = file.link;
var img = new Image();
var src = file.thumbnailLink;
img.src = src;
img.className = "th"
document.getElementById("img_list").appendChild(li).appendChild(a).appendChild(img);
}
</script>
hController.php
<?php
$fileName = $_POST['image'];
$tmpName = $_POST['image'];
$image = new \Model\Upload_Picture();
$image->image = $_POST['image'];
$fileName = uniqid()."_".basename($fileName);
$fileName = str_replace(' ', '_', $fileName);
$fileName = str_replace('-', '_', $fileName);
move_uploaded_file(tmpName, UPLOAD_PATH . 'pictures/'. $fileName );
$image->save();
?>
This code helps me to save the image into the database, but not storing it in the upload folder. I think I am making a mistake in some piece of code, help will be appreciated. Also if I upload multiple images from the dropbox account, I am not able to store all of them in my database. Only the last one is stored in db.
I want to upload multiple images at a time but it does not work. It only uploads the first image selected. I don't know what is wrong with the code below. I added the javascript tag
upload.php
if (isset($_POST['upload'])) {
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
// Loop to get individual element from the array
$validextensions = array(
"jpeg",
"jpg",
"png"
); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path.md5(uniqid()).
".".$ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 10000000) // Approx. 10MB files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
// If file moved to uploads folder.
echo $j.
').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j.
').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j.
').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
index.php
<html>
<head>
<script type="text/JavaScript" src="js/script.js"></script>
</head>
<body>
<form method="post" action="upload.php">
<div id="filediv">
<input type="file" id="file" name="file[]">
</div>
<br>
<input type="button" id="add_more" class="btn btn-primary" value="Add More Images" />
<input name="upload" id="upload" type="submit" value="Upload">
</form>
</body>
</html>
Script.js
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'images/x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
You should bot declared the count($_FILES['file']['name']) inside the loop. You have declared the outside
$count = count($_FILES['file']['name']);
for ($i = 0; $i < $count; $i++) {
// your code come here
}
I am trying to create a facebook like status update where I want a user to be able to upload images exactly like facebook does. I have the following codes which allows a user to upload and preview images and remove them by clicking on a 'X' button.
HTML Form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="newstatus" runat="server" enctype="multipart/form-data">
<textarea name="status" class="textarea newstatuscontent" placeholder="What are you thinking?"></textarea>
<input type="file" name="files[]" multiple="multiple" id="file-5" class="inputfile inputfile-4">
<div id="imgs"></div> // images preview and container
<input type="submit" name="post" value="Post" class="post-btn" id="submit" />
</form>
Ajax code to insert data to the database:
$(function() {
$("#submit").click(function() {
$(this).val("Please wait...");
var textcontent = $(".newstatuscontent").val();
/*if(media == ''){*/
if(textcontent == ''){
$('.cap_status').html("Status cannot be empty. Please write something.").addClass('cap_status_error').fadeIn(500).delay(3000).fadeOut(500);
$("#submit").val("Post");
}else{
/*}else{*/
$.ajax({
type: "POST",
url: "post-status.php",
data: {content:textcontent},
cache: true,
success: function(html){
$("#shownewstatus").after(html);
$(".newstatuscontent").val('');
$("#submit").val("Post");
}
});
}
//}
return false;
});
});
jQuery for Images preview:
function del(index) {
$('div.img_'+index).remove();
updateFiles();
}
function updateFiles() {
var fileIndexes = $('#imgs > div').map(function() {
return $(this).data('index');
}).get().join(",");
$('#files_selected').val(fileIndexes);
}
$(document).ready(function() {
$("#file-5").on('change', function() {
var fileList = this.files;
$('#imgs').empty();
if($('#imgs') != null){
$('.post-btn').css("margin-top","5px");
}
//$('#dimg').empty();
for (var i = 0; i < fileList.length; i++) {
var t = window.URL || window.webkitURL;
var objectUrl = t.createObjectURL(fileList[i]);
$('#imgs').append('<div data-index="' + i + '" class="img_' + i + '"><span class="img_' + i + '" onclick="del(' + i + ')" style="cursor:pointer; margin-right: 3px;"><b>x</b></span><img class="img_' + i + '" src="' + objectUrl + '" width="160" height="160" style="margin-right: 3px;"></div>');
j = i + 1;
if (j % 3 == 0) {
$('#imgs').append('<br>');
}
}
updateFiles();
});
});
post-status.php:
<?php
session_start();
include('config/db.php');
$time = date('Y-m-d H:i:s');
$curr_date = date('Y-m-d');
$yest = date("Y-m-d", strtotime("-1 day"));
$status = (!empty($_POST['content']))?nl2br(trim($_POST['content'])):null;
$status_fix = str_replace(array("\r", "\n"), '', $status);
$post = "INSERT INTO status(sts_status, sts_mem, sts_time)VALUES(:status, :mem, :time)";
$posq = $pdo->prepare($post);
$posq->bindValue(':status', $status_fix);
$posq->bindValue(':mem', $user_id);
$posq->bindValue(':time', $time);
$posq->execute();
$lastid = $pdo->lastInsertId();
?>
I want to combine the Image preview code with the ajax code above so that I can insert the data to the database. Now what I want?
Say for example I first selected 4 images like a.jpg, b.jpg, c.jpg, d.jpg. Then I got their preview. Then say I thought to remove b.jpg so I removed it. Now I have only the three images in preview a.jpg, c.jpg, d.jpg. Now finally, I want to rename these three files when I click on post to some random names and upload these images to the upload folder and insert their renamed names to the database.
NOTE: I want to insert and upload only those images that are in the preview div <div id="imgs"> and not from <input type="file">.
Please help me guys. I made it as much clear as possible. What I have already coded is already given above. Struggling with this problem from quite a few days. Please help me tackle this problem.
I have a Image upload form where in a user can upload Images and the after uploading a order no will be generated and the uploaded images will be shown.
My Upload Page has -
<h2>Upload Images here</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
Upload.php -
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
Javascript to let user add more images -
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
I have a table in my database which has the following fields -
Id - order_id - img_url
I don't know what loop should I create in my upload.php file to get this working -
User uploads images, then new order is created and order_id is generated which will then be updated as new entries to the table with the uploaded image urls.
Thanks
i'm having trouble uploading image with other input text form and send to ajax_php_file.php. But only image is uploaded, my input text is all empty. Would appreciate if anyone can assist here. Thanks alot.
<div id="imagebox">
<div class="image_preview">
<div class="wrap">
<img id="previewing" />
</div>
<!-- loader.gif -->
</div><!--wrap-->
<!-- simple file uploading form -->
<form id="uploadimage" method="post" enctype="multipart/form-data">
<input id="file" type="file" name="file" /><br>
<div id="imageformats">
Valid formats: jpeg, gif, png, Max upload: 1mb
</div> <br>
Name:
<input id="name" type="text"/>
<input id="cat" type="hidden" value="company"/>
Description
<textarea id="description" rows="7" cols="42" ></textarea>
Keywords: <input id="keyword" type="text" placeholder="3 Maximum Keywords"/>
<input type="submit" value="Upload" class="pre" style="float:left;"/>
</form>
</div>
<div id="message">
</div>
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var cat = document.getElementById("cat").value;
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this,myData), // Data sent to server, a set of key/value pairs representing form fields and values
//data:myData,
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
session_start();
$user_signup = $_SESSION['user_signup'];
if(isset($_FILES["file"]["type"]))
{
$name = filter_var($_POST["content_name"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$ca = filter_var($_POST["content_ca"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$desc = filter_var($_POST["content_desc"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$key = filter_var($_POST["content_key"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
$imagedata = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$imagename= ($_FILES['file']['name']);
$imagetype =($_FILES['file']['type']);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
mysql_query("INSERT INTO upload(name,picname,image,type,email,cat,description,keyword) VALUES('".$name."','".$imagename."','".$imagedata."','".$imagetype."','".$user_signup."','".$ca."','".$desc."','".$key."')");
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
the format of the formData maybe incorrect. Change it like the following:
var myData = {'content_ca':cat,
'content_desc':desc
}
i think you are using jquery
So you can use
data:$("#uploadimage").serialize(),