I have been trying my hands on PHP lately, so far so good until I hit a brick wall. Here's a little piece of code that I have. It's allowing me to upload a single file, but what I want is to be able to upload multiple files.
Here's the PHP and HTML files:
<html>
<head>
<meta charset="utf-8" />
<title>Ajax upload form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function sendfile(){
var fd = new FormData();
for (var i = 0, len = document.getElementById('myfile').files.length; i < len; i++) {
fd.append("myfile", document.getElementById('myfile').files[i]);
}
$.ajax({
url: 'uploadfile.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
</head>
<body>
<form action="uploadfile.php" method="post" enctype="multipart/form-data" id="form-id">
<p><input id="myfile" type="file" name="myfile" multiple=multiple/>
<input type="button" name="upload" id="upload" value="Upload" onclick="sendfile()" id="upload-button-id" /></p>
</form>
</body>
</html>
And the PHP file:
<?php
$target = "uploadfolder/";
//for($i=0; $i <count($_FILES['myfile']['name']); $i++){
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target.$_FILES['myfile']['name'])) {
echo 'Successfully copied';
}else{
echo 'Sorry, could not copy';
}
}//
?>
Any help would be highly appreciated.
Index.html
<html>
<head>
<title>Load files</title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
$("#loadedfiles").append(msg);
});
});
});
</script>
</head>
<body>
<div id="upload">
<div class="fileContainer">
<input id="myfiles" type="file" name="myfiles[]" multiple="multiple" />
</div>
</div>
<div id="loadedfiles">
</div>
</body>
</html>
load.php
<?php
$path="myfiles/";//server path
foreach ($_FILES as $key) {
if($key['error'] == UPLOAD_ERR_OK ){
$name = $key['name'];
$temp = $key['tmp_name'];
$size= ($key['size'] / 1000)."Kb";
move_uploaded_file($temp, $path . $name);
echo "
<div>
<h12><strong>File Name: $name</strong></h2><br />
<h12><strong>Size: $size</strong></h2><br />
<hr>
</div>
";
}else{
echo $key['error'];
}
}
?>
Related
I am trying to upload multiple images to a folder at a time by using AJAX, JQuery, and PHP. The code is running for single file upload but not running for multiple image upload.
If I am uploading a single image without loop then its working fine but in case of loop it's not working.
I am using the following code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
for (var i = 0; i < $('#file').get(0).files.length; ++i) {
names.push($('#file').get(0).files[i].name);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
//PHP Code
<?php
/* Getting file name */
echo "<script>alert('yes');</script>";
//without loop working fine
$count = count($_FILES['file']['name']);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file']['name'][$i];
/* Location */
$location = "upload/".$filename;
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
var file_data = $('input[type="file"]')[0].files;
// for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
have made changes in below code
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
And there are also changes in PHP code
<?php
/* Getting file name */
//without loop working fine
$count = count($_FILES);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file_'.$i];
/* Location */
echo $location = "upload/".$filename['name'];
/* Upload file */
if(move_uploaded_file($filename['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0'],$_FILE['file_1'] and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not, this code works for me you can try I hope it will work for you also :-)
In the loop you will need to add index of particular file
move_uploaded_file($_FILES['file']['tmp_name'][$i],$location); // $i is index
i'm trying to recreate this guide from olanod answer but isn't working for me.
I want to upload a file using AJAX but i'm getting an empty $_POST:
<form enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="text" name="as" value="asd">
<!--<button type='button' class="add_more">Add More Files</button>-->
<input type="button" value="Upload" />
</form>
and this is my script (copy paste from olanod answer ):
<script>
$(document).ready(function(){
/* $('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='upfile[]' type='file'/><br>");
});*/
$(':button').on('click', function()
{
$.ajax({
// Your server script to process the upload
url: 'ajax.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
});
</script>
As i said, i'm tring to see what i'm taking and this is the result from my php file:
array(1) {
["as"]=>
string(3) "asd"
}
I returned a text field to be sure.
P.D: Sorry for my english. I hope you can understand me, i'm trying my best!
Check this one..
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Image Upload</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="../js/jquery-3.1.1.min.js"></script>
<script src="../js/validator.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<span id="msg"></span>
<h2>Image Upload Form</h2>
<form data-toggle="validator" role="form" name="image-form" method="post" enctype="multipart/form-data" id="my-form" action="<?php $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="image">Image:</label>
<input type="file" id="image" name="image[]" data-error="Upload Image" multiple required>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#my-form").on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#my-form")[0].reset();
//alert(data);
$("#msg").html(data);
},
});
return false; //IE
}));
});
</script>
As #user2486 said,
You should use $_FILES not $_POST – user2486
He is right.
you can use this method to upload file
html-
<input type="file" class="btn btn-default" name="img2" id="img2" />
javascript-
var formData = new FormData();
formData.append('Photo', $('#img2')[0].files[0]);
$.ajax({
url: 'ImgUpload.php',
data: formData,
type: "POST",
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
}).done(function( msg ) {
I have a document with two pages. The first one sends a folder name via form submit
<form method="post" >
<input type="hidden" name="portfolio" value="directory">
<input type="submit" value="author">
</form>
the second one receives this folder name and open the files with glob function
<?php
header('Content-Type: application/json');
$directoryName = $_POST['portfolio'];
echo json_encode (glob($directoryName."/".'*.{jpg,mp4}', GLOB_BRACE));
?>
...finally images appear on the first page again via Ajax
$(document).ready(function(){
$('form').submit(function(e) {
var data = $(this).serialize();
e.preventDefault();
$.ajax({
url: "PAGE2.php",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
var html = "";
$.each(response, function(i, val) {
var fileExtension = val.substring(val.lastIndexOf('.'));
if (fileExtension == ".jpg") {
html += '<img src="'+val+'" height=250></img>';
}
else if (fileExtension == ".mp4") {
html += '<video width="320" height="240" src="'+val+'" type="video/mp4"controls autoplay loop></video>';
}
});
$("#display").html(html);
}
});
});
});
up to here no href tags...
I need to know how to display images like modal gallery with colorbox plugin.
I've tried this without success
$(document).ready(function(){
$('form').submit(function(e) {
var data = $(this).serialize();
e.preventDefault();
$.ajax({
url: "PAGE2.php",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
var html = "";
$.each(response, function(i, val) {
var fileExtension = val.substring(val.lastIndexOf('.'));
if (fileExtension == ".jpg") {
html += '<img src="'+val+'" height=250></img>';
}
else if (fileExtension == ".mp4") {
html += '<video width="320" height="240" src="'+val+'" type="video/mp4"controls autoplay loop></video>';
}
});
$("#display").html(html);
$("#link").colorbox({ inline:true, href: "#display"});
}
});
});
});
<body>
...
<div id="display" style="display:none;"></div>
<a id="link" style="display:none"></a>
</body>
PAGE1.php
<!DOCTYPE HTML>
<html lang="">
<head>
<meta charset="UTF-8">
<title>page1</title>
<link rel="stylesheet" href="colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="../jquery.colorbox.js"></script>
<script>
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({
html:data,
rel:'group1'
});
},
'html');
return false;
});
});
</script>
</head>
<body>
<div class="container">
<form action="page2.php" method="post" id="formID">
<input type="hidden" name="var" value="directory">
<input type="submit" value="author">
</form>
</div>
</body>
</html>
PAGE2.php
<!DOCTYPE HTML>
<html lang="">
<head>
<meta charset="UTF-8">
<title>page2</title>
</head>
<body>
<?php
$variable = $_POST['var'];
$img_dir = $variable . "/";
foreach(glob($img_dir . '*.jpg') as $image) {
echo '<img src="'.$image.'">'.'<img class="group">';
}
?>
</body>
</html>
I have the most simple case of image upload. When I run this as a separate example it DOES work. When I incorporate the same .js code into my project's javascript code, and try the upload from my html page (.js and .php codes identical, id's and names adjusted etc.), it doesn't work.
html:
<html>
<head>
<title>HTML5 File API</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="main">
<h1>Upload Your Images</h1>
<input type="file" name="images" id="images"/>
<input type="submit" id="submitImages" onclick="submitImages()">
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="upload.js"></script>
</body>
</html>
javascript:
function submitImages(){
if (window.FormData) {
formdata = new FormData();
}
file = document.getElementById('images').files[0];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images[]", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
}
});
}
}
php:
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
The message I get from server when I attempt the upload from my project:
POST-->POST:
Source
-----------------------------2656620091882 Content-Disposition: form-data; name="images[]"; filename="dock_2.jpg" Content-Type: image/jpeg ÿØÿáa"Exif��MM�*��
etc.
POST-->RESPONSE:
<br />
<b>Notice</b>: Undefined index: images in <b>C:\XAMPP\htdocs\Projects\DockMapper\add_edit_upload_images.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Invalid argument supplied for foreach() in <b>C:\XAMPP\htdocs\Projects\DockMapper\add_edit_upload_images.php</b> on line <b>3</b><br />
<h2>Successfully Uploaded Images</h2>
It seems that something is sent to the server, but that it is not received on the server. When I run: print_r($_FILES); the array is empty. I spent probably two days over this and I couldn't find the problem. Any suggestions? Big thanks.
Use this
For example
Jquery
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data)
alert(form_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
PHP
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Ok, this was the issue:
In my project's html file, jquery was included inside the HEADER with these lines:
<head>
...
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
...
</head>
It worked when I deleted those lines, and included ONLY the following ajax library, inside the FOOTER:
<html>
<body>
...
</body>
...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
...
</html>
I want to upload multiple files and have a file called test.php with this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(function(){
var myVar;
$('form').submit(function(){
myVar = setInterval(ajax, 1000);
});
var ajax = function() {
$.ajax({
url: 'test2.php',
type: 'post',
success: function(ajax_result){
$('.result').html(ajax_result);
if (!ajax_result) {
clearInterval(myVar);
}
},
error: function(){
alert('error');
}
});
};
});
</script>
</head>
<body style="width:100%; height:100%;">
<form action="test2.php" target="iframe" method="post" enctype="multipart/form-data" >
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="fil" />
<input name="file[]" type="file" multiple />
<input type="submit">
</form>
<iframe id="iframe" name="iframe"></iframe>
<div class="result" style="width:100%; height:100%;"></div>
</body>
</html>
and a file called test2.php with this code:
<?php
session_start();
if (isset($_FILES['file'])){
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
move_uploaded_file($_FILES['file']['tmp_name'][$i],'a/'.$_FILES['file']['name'][$i]);
}
}
if (isset($_SESSION[$key = ini_get("session.upload_progress.prefix") . 'fil'])) {
var_dump($_SESSION[$key]);
} else echo false;
?>
Now I want before sending files to server to detect the number of files selected via their names in the client side.
How can I do this?
$('form').submit(function() {
var numberOfFilesAboutToBeSubmitted = $("[name='file[]']", this ).prop("files").length;
});
Note that you are not submitting any files with your ajax request, it has no association with your form at all.
Also note that this doesn't work in IE < 10