I'm using thid code this basically helping me getting file which user drops on browser and then post it to php and echoing file name but the problem is with the array in php when ever i drop 2 files and call the php file and try to echo the count of files it gives me 5 always and it echos the 2 file names and + othes as undefined index.... and if i upload 5 files it show all 5 with no problem....plz help me why this is happing...
Here is my jquery code:
function handleFiles(droppedFiles) {
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) {
// checks if any files were dropped
for(var f = 0; f < droppedFiles.length; f++) {
// for-loop for each file dropped
alert(droppedFiles[f]['name']);
uploadFormData.append("files[]",droppedFiles[f]);
// adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "try.php?size="+s, // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
return false;
}
Here is my php code :
if(isset($_FILES["files"])) {
for ($i=0;$i<count($_FILES['files']);$i++) {
echo $_FILES['files']['name'][$i];
echo "\n";
}
}
It doesn't work this way. $_FILES is an associative array containing the uploaded files, indexed by the field name. Each entry has exactly five elements: name,tmp_name,size,type and error. Each of these elements is an array containing as many elements as the uploaded files.
So if you count($_FILES['files']), the result will always be 5. But if you count($_FILES['files'][$xyz]) where $xyz is any of the above keys, that will be the number of uploaded files.
So your code would work like this, for example:
if(isset($_FILES["files"]))
{
for ($i=0;$i<count($_FILES['files']['name']);$i++)
{
echo $_FILES['files']['name'][$i];
echo "\n";
}
}
or better yet (for readability, if nothing else):
if(isset($_FILES["files"]))
{
$filenames=$_FILES['files']['name'];
for ($i=0;$i<count($filenames);$i++)
{
echo $filenames[$i];
echo "\n";
}
}
Related
As stated, I have a problem with the response if I upload multiple files at once.
For example, I upload a.jpg and b.jpg.
In the next step, I upload b.jpg and c.jpg.
My PHP script checks the names for duplicity and finds one in b.jpg but as response, I got each images flagged with
error - file already there.
I can't differ the responses individually.
I initialize my dropzone via jquery:
myDropZone = $("#dropzone").dropzone({
autoProcessQueue: false,
uploadMultiple: true,
xx: xx
init:function(){
var self = this;
// check error and some other states
self.on("error", function (file, response) {
console.log("error: "+file);
console.log("error-response: "+response);
}
// set process
$("#actions .start").click (function(file){
self.processQueue();
}
}
});
I use uploadMultiple for multiple fileupload, I disabled the autoprocess and binded the function processQueue() to a button of my liking.
So far so good.
No I have my php-script processing the data. It should be called once because of the uploadMultiple parameter.
if (!empty($_FILES)) {
// resort array for easy processing
for($i = 0 ;$i < count($_FILES['file']['name']) ; $i++) {
$fileArrays[] = array_column ( $_FILES['file'], $i);
}
foreach($fileArrays as $file) {
$upload = array();
if(file_exists($file[0])) {
$upload[] = "File already there.";
}
// some other validations...
}
if(empty($upload)) {
//move_uploaded_file()
http_response_code(200);
} else {
print_r($upload);
http_response_code(404);
}
But now all uploads get all responses, whether they are true or not.
For example, I upload b.jpg and c.jpg, where b.jpg already exists. Both images get the success icon.
Now I upload d.jpg and c.jpg (note the order), where c.jpg already exists and both images the the error
File already there
Does anybody have the same problem with the response?
Maybe I'm doing the php-validation wrong?
Or do I have to handle the dropzone-event-parameter (success, etc.) in another way? I tried successmultiple, completemultiple, etc. but with no success.
"Solved" it by switching from ProcessQueue to:
self.getQueuedFiles().forEach(function(element) {
self.processFile(element);
});
Brougth some other problems with it but they were solvable.
I have a page that allows users to upload multiple files and preview them without refreshing the page using jquery. In php I generate a unique file_id for each filename which I would then like to pass back in to JQuery and use it to load up the preview image etc.
I hope I have explained myself clearly.
Thanks for any pointers!
The PHP code:
// php code to upload file and generate unique file id. then...
if (move_uploaded_file($main_image, $file)) {
echo "success";
echo $file_id; // <--- I WANT TO PASS THIS VARIABLE BACK IN TO JQUERY
} else {
echo "error";
}
The J Query Code:
$(function(){
var btnUpload=$('#upload_main');
var mestatus=$('#mestatus');
var button=$('#button');
var files=$('#main_file');
new AjaxUpload(btnUpload, {
action: 'classified-ads/upload-classified-image.php?filenumber=1',
name: 'file1',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|'')$/.test(ext))){
// extension is not allowed
mestatus.text('Only JPG, PNG or GIF files are allowed');
return false;
}
mestatus.html('<img src="extras/ajaxuploader/progress_bar.gif" height="30" width="340">');
button.html('Loading...');
$('#upload_main').removeClass('hover').addClass('upload_button_loading');
},
onComplete: function(file, response){
//On completion clear the status
mestatus.text('Photo Uploaded Sucessfully!');
button.html('Change Photo');
$('#upload_main').removeClass('upload_button_loading').addClass('upload_button');
//On completion clear the status
files.html('');
//Add uploaded file to list
if(response==="success"){
var file2 = file.replace(/\s/g, "_");
var file_id= file_id;
$('<div></div>').appendTo('#main_file').css('background-image', "url(/ht/classified-ads/temp_images/prev1_<?php echo $parsed_user;?>_"+file_id+")").addClass('main_success');
$("#image1_temp").val("main1_<?php echo $parsed_user;?>_"+file_id+"");
$("#thumbnail_temp").val("thumbnail_<?php echo $parsed_user;?>_"+file_id+"");
} else{
$('<li></li>').appendTo('#main_file').text(file).addClass('error');
}
}
});
});
In your PHP:
$response = array('result' => 'success', 'file_id' => $file_id);
echo json_encode($response);
In your jQuery:
var obj = $.parseJSON(response);
You would then check whether the response was a success with if (obj.result == 'success') and you'd get your file_id with obj.file_id
The simplest way is to do this allowing for MULTIPLE values to be returned:
// Make a variable to hold data to send back and keep track of your separator
$data = '';
$separator = 1;
// Put this in a loop, your loop will depend on how many file uploads you have
// I did not do the loop for you
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
if ($separater==1){
$data .= $file_id;
} else {
$data .= ','.$file_id;
}
$separater++;
}
// Now outside the loop echo the results back
echo $data;
With this info echoed back you can manipulate it with Javascript (Jquery). Just use something like spli(','); which gives you an array of the file names you needed.
If you only want one value to come back, meaning you only have one file id to send back foregt everything about the loop and the PHP would be this:
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
$data = $file_id;
// Now echo the results back
// Its been a while since I've done this but there may be times its ok to use return
echo $data;
} else {
// Handel error here
echo "error";
}
Now based off your code this echoed information should be picked up and processed here:
onComplete: function(file, response){ ... }
Instead of looking for "Success" you need to change your code to look for a file id or something like error instead (which is easier) like so:
if(response!=="error"){
// Now you can use your variable "response" here since it contains the file id
} else {
// Handle the error
}
The reason I gave you a long explanation about getting multiple values back is because that is more common as you start making more advanced forms and it wouldn't hurt to use now. This way you can allow multiple file uploads for example. What I do for example when using AJAX is echo back something like this:
1::value,value,value
Now I just split that into arrays first by :: and then by , this line for example says No Error Happened (1 which as we know is also TRUE) and here is your data: value,value,value which you can now use for things in your Jquery or just print to the document.
You should look at the Jquery AJAX page for in depth examples and explanations, it explains the trouble you ran into getting results back. Look at .done .success .complete especially.
I have seen many topics about this problem but none of them got a legit answer or a including PHP file.
I want to make a drag & drop saving tool. The problem is that my files are not getting uploaded to my ftp folder.
I got the following code:
HTML:
<div id="drop_zone">
<p>Drop Here</p>
</div>
<form enctype="multipart/form-data" id="yourregularuploadformId">
<input type="file" name="files[]" multiple="multiple">
</form>
JS:
$(function() {
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
etc.... dropping part
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
files = evt.dataTransfer.files;
uploadFile(files);
etc... getting file to my method
function uploadFile(droppedFiles){
// add your files to the regular upload form
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) { // checks if any files were dropped
for(f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
uploadFormData.append("files[]",droppedFiles[f]); // adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "php/uploadFile.php", // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
}
Got the above code from another topic. (alert(uploadFormData); -> gives me a Formdata aboject)
PHP:
move_uploaded_file($_FILES["file"]["tmp_name"],
"ftp/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
Can't make it work :<
The message i get from the callback function in my JS is:
Undefined index: file
Your PHP code needs to iterate over all of the files in the request. Based on your javascript, your PHP code should look something like this:
foreach ($_FILES["files"] as $file) {
move_uploaded_file($file['tmp_name'], $target);
}
The $target variable must point at the local destination for your file. See the PHP manual for more details.
Here's the plugin: https://github.com/blueimp/jQuery-File-Upload
I'm having a problem getting the response I want from the plugin after uploading a file.
On the page with the plugin, I have the following
$('#fileupload').fileupload(
'option',
{
'maxNumberOfFiles' :1,
'url' : '/admin/upload_handler.php'
}
);
In upload_handler.php I successfully retrieve the uploaded files from $_FILES and do stuff, then send a response back in JSON. I've confirmed using Firebug that the response is in the proper format:
[
{
"url" : "image_url",
"thumbnail_url" : "image_th_url",
"delete_url" : "test",
"delete_type" : "DELETE",
"name" : "foobar.jpg",
"size" : 7419
}
]
But the callback can't find the files array, and I get the error: 'Empty file upload result'. I feel like I'm missing something crucial here--I can't find anything in the docs, forums, or Stack Overflow. I appreciate any help.
Since the version 5 of the plugin, the json response has changed: https://github.com/blueimp/jQuery-File-Upload/wiki/JSON-Response
So you just have tweak your upload class with:
$filejson = new stdClass();
$filejson->files[] = $fileArray;
return json_encode($filejson);
And you're done
Your return needs to be enclosed in a files array, like this:
{"files": [
{
"name": "picture1.jpg",
"size": 902604,
"url": "http:\/\/example.org\/files\/picture1.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
"deleteType": "DELETE"
},
{
"name": "picture2.jpg",
"size": 841946,
"url": "http:\/\/example.org\/files\/picture2.jpg",
"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture2.jpg",
"deleteUrl": "http:\/\/example.org\/files\/picture2.jpg",
"deleteType": "DELETE"
}
]}
in particular, the requirement is: Note that the response should always be a JSON object containing a files array even if only one file is uploaded.
via :: https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
The "Empty file upload result" will occur when adding HTML (and in programmatical result DOM) objects to the template that are outside of the <tr class="template-upload fade"> HTML tag, e.g.: let's say you add another <tr> to the template
This will result in the file(s) being uploaded correctly and for every uploaded file you will get the "Empty file upload result" once.
Seems to have to do something with the JS template engine.
This can be fixed in jquery.fileupload-ui,js, right after line 128
Original code:
// Callback for successful uploads:
done: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
files = that._getFilesFromResponse(data),
template,
deferred;
if (data.context) {
data.context.each(function (index) { // LINE 128
var file = files[index] ||
{error: 'Empty file upload result'},
deferred = that._addFinishedDeferreds();
Add the following code after line 128:
if (!$(data.context[index]).hasClass(that.options.uploadTemplateId)) { return true; }
Resulting code:
// Callback for successful uploads:
done: function (e, data) {
var that = $(this).data('blueimp-fileupload') ||
$(this).data('fileupload'),
files = that._getFilesFromResponse(data),
template,
deferred;
if (data.context) {
data.context.each(function (index) { //LINE 128
if (!$(data.context[index]).hasClass(that.options.uploadTemplateId)) { return true; } // YOUR ADDED LINE
var file = files[index] ||
{error: 'Empty file upload result'},
deferred = that._addFinishedDeferreds();
Hope this helps others :)
OK, this seems like it is not a jQuery problem, but rather a server-side issue. In my case it is a PHP script, which needed tweaking as follows.
See function post(), edit this line
$json = json_encode($info);
to
$json = json_encode(array($this->options['param_name'] =>$info));
and I had to also edit the echo at the last line of the function; instead of
echo $json;
there is now
echo str_replace('\/','/',$json);
It seems to work fine returning a correct json array. Hope it helps.
In my case I, i modified the jquery.fileupload-ui.js file to look for the JSON result directly.
Change this snippet
if (data.context) {
data.context.each(function (index) {
var file = files[index] ||
{error: 'Empty file upload result'};//CHANGE
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
To This
if (data.context) {
data.context.each(function (index) {
var file = data._response.result[index] ||
{error: 'Empty file upload result'};//TO THIS
deferred = that._addFinishedDeferreds();
that._transition($(this)).done(
function () {
As mentioned before this happens because the server response is not what the plugin expects (which is a files array as shown here).
If you don't (or cannot) want to change the backend, a solution is to replace the result object in the response with the result object the plugin expects (which then contains the files array).
This can be done in the fileuploaddone event.
Let's assume that this is the JSON response returned from the server once the upload is done:
data.result holds the server response:
.bind('fileuploaddone', function(e, data) {
//this will now contains the server response
//as per the attached image: an array of elements
data.result;
});
We want to replace the result object with a new one that can be parsed by the blueimp plugin, let's define it (note: this is an object that contains an array of files, as per the plugin docs).
//tempFolder is optional
var filesUploaded = { "files": [], "tempFolder": null };
Replacing the result object:
.bind('fileuploaddone', function(e, data) {
//creating a file object in the format the jquery plugin is expecting
var file = {
deleteType: "DELETE",
deleteUrl:"#",
type: data.result[0].MimeType,
thumbnailUrl : "#",
url: "#",
name: data.result[0].Name,
size: data.result[0].Size
}
//adding it to the file list
filesUploaded.files.push(file);
data.result = null;
//replacing the server response with the 'custom' one we just created
data.result = filesUploaded;
});
The plugin should now render fine as it will be parsing the expected JSON schema and you won't get the "Empty file upload result" message anymore.
For me it was the uploads file size.
i tuned those php.ini parameters:
memory_limit
post_max_size
upload_max_filesize
max_file_uploads
I'm looking for a php script server side that load an image in a div on client side.
first shot:
ajax.php
if((isset($_POST['id'])) && ($_POST['id']=="loadphoto") && (ctype_digit($_POST['idp']))) {
$query=mysql_query("SELECT articleid, photoid FROM articles_photos WHERE id='".$_POST['idp']."'", $mydb);
if(mysql_num_rows($query)!=0){
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
$path="./articles/photos/".$row[0]."/".$row[1];
}
echo $path;
}
}
myjs.js
function loadPhoto(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'idp='+escape(mexid)+'&id=loadphoto',
success: function(msg) {
$('.articleviewphoto1').find("img").each(function(){
$(this).removeClass().addClass('photoarts');
});
$('#'+mexid).removeClass().addClass('photoartsb');
$('#visualizator').html('<img src="'+msg+'" class="photoartb" />');
}
});
return false;
}
Are you looking to host a list of possible images in the PHP file and load different images based on the id you send? If so, you can set:
$Img = $_POST['idp'];
And use a switch statement to pass back the image file path:
switch ($Img){
case (some_value):
echo 'images/some_file.jpg';
break;
case (another_value):
echo 'images/another_file.jpg';
break;
}
Then place the file path in an tag and load that into $('#visualizator').html();
Am I on track at least with what you want? If so, I can flesh the answer out a bit.
I'm assuming the image already exists somewhere and isn't being generated on the fly. In the PHP script, you can access the variables with $_POST['idp'] and $_POST['id']. Do whatever processing you need, and then simply echo the URL. The variable msg in the javascript will be everything echo'd by the PHP script. Then, you could just do this:
$('#visualizator').html('<img src="' + msg + '" />');