I have a code that sends multiple files to the server using FileReader to display images and FormData to send via ajax.
My code works, the problem is to show the multiple progress bars. If I select only one file, it works.
But if I select multiple files it shows the progress of all files in the last progress bar.
Can anyone help?
(function () {
var input = document.getElementById("images")
function showUploadedItem (file, id) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var template = '<li>'+
'<img src="'+e.target.result+'">'+
'<br />'+
'<progress min="0" max="100" value="0" id="'+id+'"></progress>'+
'</li>';
$("#image-list").append(template);
};
})(file);
reader.readAsDataURL(file);
}
input.addEventListener("change", function (evt) {
for (var i=0, j=this.files.length; i<j; i++) {
file = this.files[i];
formdata = new FormData();
formdata.append("images[]", file);
var xhr = new XMLHttpRequest();
xhr.id = "progress_" + Math.floor((Math.random() * 100000));
xhr.addEventListener("loadstart", function(e){
showUploadedItem(file, xhr.id);
});/*
xhr.addEventListener('progress', function(e) {
}, false);*/
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
$("#" + xhr.id).attr('value', Math.floor((e.loaded / e.total) * 100) )
};
/*xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};*/
xhr.open('post', 'upload.php', true);
xhr.send(formdata);
}
}, false);}());
My Php Code:
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</h2>";
My html;
<div id="main">
<div style="padding-bottom:10px">
<input type="file" name="images" id="images" multiple />
</div>
<ul id="image-list"></ul>
<br style="clear:both">
</div>
You have a closure issue, use this instead of xhr to refer to the current XMLHttpRequest object in the event callbacks;
function(e){
showUploadedItem(file, this.id);
});
function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
$("#" + this.id).attr('value', Math.floor((e.loaded / e.total) * 100) )
}
Related
I'm not a php programmer. Someone ask me help for a web server with problem. I fix everything and update PHP 5.4 to 5.6. Everything work fine on his php program, except file upload.
Message: getimagesize(var/www/myserver/admin/uploads/temp/test.jpg): failed to open stream: No such file or directory
error on this line: $img_info = getimagesize("uploads/temp/$filename");
if($_POST['fileselect'][0] != "")
$filename=$_POST['fileselect'][0];
else
$filename=$_POST['dragfile'];
if(strlen($filename) > 3){
$finalname=time(); //Set a unique filename by the UNIX time
//Convert to jpg if tiff
$img_info = getimagesize("uploads/temp/$filename");
if($img_info['mime'] == "image/tiff"){
$clearname=explode(".", "$filename")[0];
system("convert uploads/temp/\"$filename\"[0] uploads/temp/$clearname.jpg");
unlink("uploads/temp/$filename");
$filename=$clearname.".jpg";
}
The problem probably come from a new code formulation in php5.6, any idea how to fix that ?
UPDATE 2: FILE UPLOAD section...
part of form.php
<form method="post" class="form-horizontal">
<input type="hidden" id="to_upload" name="to_upload" value="/upload.php">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000000" />
<input type="hidden" id="id_produit" name="id_produit" value="<?php echo $this->mdl_inventory->form_value('idproduit'); ?>" />
<div class="control-group">
<label class="control-label">Nouveau (jpeg): </label>
<div class="controls">
<input type="file" id="fileselect" name="fileselect[]">
</div>
</div>
Does the name fileselect[] can be the problem ? How can i check if the script go in "upload.php" ?
part of upload.php
/* read the source image */
$source_image = imagecreatefromjpeg("$src");
$width = imagesx($source_image);
$height = imagesy($source_image);
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'uploads/temp/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}else {
// form submit
$files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
ajax script filedrag.js (upload)
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/tiff" ) && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("to_upload").value + "?idproduit=" + $id("id_produit").value, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
$('#dragfile').attr('value', file.name);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
//submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The syntax for the code mentioned is correct for 5.6, no issues with that.
I don't see permissions as the issue as well, otherwise you'd have gotten a 'Permission denied' error.
So, most likely, it looks like, the file that you are looking for does not exist in the folder.
the error was here:
xhr.setRequestHeader("X_FILENAME", file.name);
X-filename... i think it's APACHE UPDATE problem.
Thanks for help.
I am working on Codeigniter, i am facing one problem i have to show the user error message when he is uploading any other file type to server using ajax. I do not want to load view again to show the error message. My code is as follows:
Please help me to solve my problem.'
View:
function upload_video_Data(a)
{
var fd = new FormData(document.getElementById('posting_comment_'+a));
fd.append("file_m_id",a);
var bar = $('.bar');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("nameTest").value=xhr.responseText;
}
}
xhr.open("POST", "Dashboard/do_upload_video");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
$("#status").animate( { width: percentComplete.toString()+"%"}, 5);
}
}
}
Controller:
public function do_upload_video()
{
$lecture_id=$_POST['file_m_id'];
$output_dir = "./uploads/";
$fileName = $_FILES["save_movie_".$lecture_id]["name"];
if(!move_uploaded_file($_FILES["save_movie_".$lecture_id]["tmp_name"],$output_dir.$fileName))
{
echo '0';
}
else
{
echo '1';
}
}
Use this code before your ajax to validate the extension of file
var ext = $('#my_file_id').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
Now your code look like this
function upload_video_Data(a)
{
var ext = $('#my_file_id').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
return false;
}
var fd = new FormData(document.getElementById('posting_comment_'+a));
fd.append("file_m_id",a);
var bar = $('.bar');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("nameTest").value=xhr.responseText;
}
}
xhr.open("POST", "Dashboard/do_upload_video");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
$("#status").animate( { width: percentComplete.toString()+"%"}, 5);
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there any AJAX PHP Jquery MySQL plugin that you can upload multiple files (preferably drag-drop), that add's datetimestamp to the actual FILENAME (where it stores in a folder on the server). Also where you can choose a tile and description that inserts into a MySQL database (the mysql row is going to have the columns as follows: USER_ID,IMAGE_FILENAME,TITLE,DESCRIPTION). I am attempting to make a database for the pictures for my users of my user-based website.
http://hayageek.com/drag-and-drop-file-upload-jquery/
I've tried modding this properly, just couldn't get it to work...I like the design, functions aren't quite there. Any ideas or suggestions that meet my question?
<h1>Source Javascript</h1>
function sendFileToServer(formData,status)
{
var uploadURL ="<? echo $dyn_www; ?>/php_parsers/upload.php"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);
$("#status1").append("");
}
});
status.setAbort(jqXHR);
}
var rowCount=0;
function createStatusbar(obj)
{
rowCount++;
var row="odd";
var filename = this.filename;
if(rowCount %2 ==0) row ="even";
this.statusbar = $("<div class='statusbar "+row+"'></div>");
this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
this.success = $("<i style=\"color:#009900;display:none\" class=\"fa fa-check-circle\"></i>").appendTo(this.statusbar);
this.titleOfImage = $("<div class='title'><input name='image_file_name' value='"+file_date+"' /><button id=\"title_button_"+row+"\" type=\"submit\"><i class=\"fa fa-chevron-circle-right\"></i></div></div>").appendTo(this.statusbar);
obj.after(this.statusbar);
this.setFileNameSize = function(name,size)
{
var sizeStr="";
var sizeKB = size/1024;
if(parseInt(sizeKB) > 1024)
{
var sizeMB = sizeKB/1024;
sizeStr = sizeMB.toFixed(2)+" MB";
}
else
{
sizeStr = sizeKB.toFixed(2)+" KB";
}
this.filename.html(name);
this.size.html(sizeStr);
}
this.setProgress = function(progress)
{
var progressBarWidth =progress*this.progressBar.width()/ 100;
this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
if(parseInt(progress) >= 100)
{
this.abort.hide();
this.success.show();
this.titleOfImage.show();
}
}
this.setAbort = function(jqxhr)
{
var sb = this.statusbar;
this.abort.click(function()
{
jqxhr.abort();
sb.hide();
});
}
}
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var fulldatetime = ""+ curr_date + "-" + curr_month + "-" + curr_year +"";
var filename = files[i].name;
var ext = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();
var allowed= "";
if(ext == "jpg" || ext == "png" || ext == "gif" || ext == "jpeg")
{
var fd = new FormData();
fd.append('file', files[i]);
var status = new createStatusbar(obj); //Using this we can set progress.
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status);
}else
{
alert("You are only allowed to upload .jpg, .png, & .gif");
}
} //end for
}
$(document).ready(function()
{
var obj = $("#dragandrophandler");
obj.on('dragenter', function (e)
{
e.stopPropagation();
e.preventDefault();
$(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e)
{
e.stopPropagation();
e.preventDefault();
});
obj.on('drop', function (e)
{
$(this).css('border', '2px dotted #0B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
//We need to send dropped files to Server
handleFileUpload(files,obj);
});
$(document).on('dragenter', function (e)
{
e.stopPropagation();
e.preventDefault();
});
$(document).on('dragover', function (e)
{
e.stopPropagation();
e.preventDefault();
obj.css('border', '2px dotted #0B85A1');
});
$(document).on('drop', function (e)
{
e.stopPropagation();
e.preventDefault();
});
});
</script>
Together with your code, try:
Replace this block:
/*
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var fulldatetime = ""+ curr_date + "-" + curr_month + "-" + curr_year +"";
*/
With:
var d = new Date();
var fulldatetime = d.getDate() + "-"
+ (d.getMonth()+1) + "-"
+ d.getFullYear() + "--"
+ d.getHours() + "-"
+ d.getMinutes() + "-"
+ d.getSeconds();
And then:
var filename = files[i].name;
var ext = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();
/* this line added */
var file_date = fulldatetime+'_'+filename;
var allowed= "";
if(ext == "jpg" || ext == "png" || ext == "gif" || ext == "jpeg")
{
var fd = new FormData();
fd.append('file', files[i]);
/* this line added */
fd.append('fileDateTime',file_date);
var status = new createStatusbar(obj); //Using this we can set progress.
The rest of your code remains the same. You can address the new file name with $_POST['fileDateTime']; on your upload.php
Addition:
To pass the renamed file to createStatusbar(), change the function definition:
from:
/* function createStatusbar(obj) */
to:
function createStatusbar(obj,file_date)
and during it's call:
/* var status = new createStatusbar(obj); //Using this we can set progress.*/
to:
var status = new createStatusbar(obj,file_date); //Using this we can set progress.
file_date is the variable that holds the new file name, you can then use it as you need.
I need to upload more than 10000 images togather for a project in php. After changing max_file_uploads to 1000 in php.ini i can only upload 200 photos at a time.now i'm using uplodify but it allows only 999 files to be uploaded at a time.how can increase this limit to 2000?here's my code in the index page`
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadify({
'uploadLimit' : 2000,
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>'
},
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php'
});
});
</script>
May be you can uploading files with using File API (HTML5) and creat queue with files with some count files?
I think that this is real.
This is my code. Quick wrote. You can change it by yourself.
<!DOCTYPE HTML>
<html>
<body>
<head><meta charset="utf-8"></head>
<form onSubmit="upload_files(this); return false;">
<input type="file" name="files_upload" multiple>
<input type="submit" value="Upload">
</form>
<script>
var tests = {
filereader: typeof FileReader !== 'undefined',
formdata: !!window.FormData
};
var limit = 199; // Limit files in queue.
function upload_files(form) {
var files = form.elements.files_upload.files;
var files_length = files.length;
var files_count = 0;
var xhr = new XMLHttpRequest();
var formdata = new FormData();
for (var i = 0; i < files_length; i++) {
if ((files_count < (limit - 1))) {
formdata.append('files[' + i + ']', files[i]);
files_count++;
}
else {
files_count = 0;
formdata.append('files[' + i + ']', files[i]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploader.php');
xhr.send(formdata);
var formdata = new FormData();
}
}
if (files_count < limit && files_count > 0) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploader.php');
xhr.send(formdata);
}
}
</script>
</body>
</html>
I am new to XMLHttpRequest and I have been using it as a AJAX file uploader using JavaScript's FormData().
The problem I am having is that it seems to upload fine, although I think it is not sending it to the right PHP file or my PHP is wrong because nothing is displayed in the folder where pictures should be.
At the moment, I don't know how to view the returned html data
JavaScript:
$("#form").submit(function(event) {
event.preventDefault();
event.stopPropagation();
var form = $(this);
var file = document.getElementById("file");
var data = new FormData();
var onerror = function(event) {
alert("An error occoured!");
}
var onprogressupdate = function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total * 100;
$("#progress").html(percent+"%");
}
}
var onreadystatechange = function(event) {
if(request.status == 200 && request.readyState == 4) {
alert("Uploaded!");
$("#progress").hide();
$("#progress").html("");
}
else {
alert("Alternative state and/or status");
console.log("state: " + request.state);
console.log("readyState: " + request.readyState);
}
}
for(var i = 0; i < file.files.length; i++)
data.append('file[]', file.files[i]);
$("#progress").show();
$("#progress").html("Uploading files...");
var request = new XMLHttpRequest();
request.upload.addEventListener("error", onerror);
request.upload.addEventListener("progress", onprogressupdate);
request.upload.addEventListener("readystatechange", onreadystatechange);
request.open("post", "upload.php");
request.setRequestHeader("Content-type", "multipart/form-data");
request.send(data);
});
Upload page
<?php
if(isset($_FILES["file"])) {
$f = $_FILES["file"];
$dir = "data";
if(!file_exists($dir))
mkdir($dir);
foreach($f["name"] as $k => $name) {
$file = $dir."/".$name;
if($f["error"][$k] == 0 && move_uploaded_file($f["tmp_name"][$k], $file)) {
$uploaded[] = $file;
}
}
die(json_encode($uploaded));
}
?>
Don't set the content type, its set automatically.
Create your FormData object with form element you want to send:
var data = new FormData(this);
instead of
var data = new FormData();
The syntax of the FormData is
new FormData (optional HTMLFormElement form)
without the argument, it is empty, see the reference.