jQuery-File-Upload used for UI only? - php

I would like to upload multiple files. The use case is: users on my website can upload multiple photographs.
Right now I am just using
<input type="file" name="myfiles" multiple="multiple">
This works well, but I want more. I'd like a nice interface showing the user what is uploaded AND for it to be more clear about which files are being uploaded.
https://github.com/blueimp/jQuery-File-Upload
So this blueimp jquery file upload script has beautiful UI and is just what I'm looking for. However there are a few issues:
1) I would like to submit the form to a php file which will DECIDE if the files get uploaded or not.
2) My form has many (many..) other fields. I would like this to submit via plain old post submit button along with the rest of my form. Is this possible?
If not, can someone recommend a better option?
Thanks!

All of the above is possible with the blueimp file upload plugin.
1) Decide if files get uploaded or not
Use the add: option in the plugin to make a separate ajax call to the server with the filenames added, and use the response to filter the list of files to be uploaded.
2) Add other data from the form to the upload
Use the formData: option in the plugin to add the other fields in a form to be passed to the server upon submit.
So something like the following:
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
loadImageMaxFileSize: 15000000, // 15MB
formData: $("#myForm").serializeArray()
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.ajax(
url: "/checkfiles",
data: { files: data.files },
success: function(result) {
// assume server passes back list of accepted files
$.each(result.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append(file.error);
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
});
}).on('fileuploadfail', function (e, data) {
$.each(data.result.files, function (index, file) {
var error = $('<span/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
});
});
});

Related

TCPDF - AJAX - Download file without saving it to webserver from AJAX call

I have an AJAX call to the create_pdf.php page:
$('body').on('click', '.PrintButtonWithClass', function (event) {
var1 = $('#id1').val();
var2 = $('#id2').val();
dataString='var1='+var1+'&var2='+var2+'&pdf_name=PdfName&pdf_creator=myname';
$.ajax({
type: 'post',
url: '/path/to/createpdf/file/create_pdf.php',
data: dataString,
success: function (data) {
alert('success');
}
});
});
In create_pdf.php I tried to use this line to download the file:
$pdf->Output(str_replace(' ','_',utf8_decode($_POST['pdf_name'])).'.pdf', 'D');
I tried also the FD and I parameters with no success, the file does not get downloaded.
How can I force downloading the file created without saving it to the webserver and without redirecting user to any other page? I want him to stay on the same page, and that the browser pops up a (download or preview dialog box) for the PDF. Is there any way to do it?
EDIT : create_pdf.php is Waiting for POST variables. and uses them to create the HMTL for the pdf.
You can try to submit the form to a new window( like a popup ):
<form method="post" id="myform" action="your_url">
<input name="param1">
</form>
And in javascript
// create popup window
var wind = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');
// submit form to popup window
$("#myform").attr("target", "__foo");
Do not forget to send content-type header from php:
header("Content-Type", "application/pdf");
Edit:
Browsers should display your pdf content and also show download or print options.
The code is not tested but I think it would do what you requested;
I found a work-around for my problem.
I did an AJAX call inside another AJAX call.
the first AJAX call creates the file on webServer and opens the file in a new Window.
In his success parameter I do the following:
The second AJAX call that deletes the file from Server.
$.ajax({
type: 'post',
url: '/path/to/create_pdf.php',
data: dataString,
success: function (data) {
window.open(
data,
'_blank' // <- This is what makes it open in a new window.
);
window.setTimeout(function () {
dataString2 = 'Downloaded=true';
$.ajax({
type: 'post',
url: '/path/to/create_pdf.php',
data: dataString2,
success: function (data) { alert(data); }, // handler if second request succeeds
});
}, 5000);
},
});
Using this answer to my similar request : send a csv file from php to browser
I needed to (1) get and display a pdf in another window; and
(2) get a CSV file and prompt for saving.
I have 2 simple buttons on the page (http://potoococha.net/) for each. Here is the code:
function getCSVText(evt) {
if (currentChecklistCountry) {
var form = $('<form method="post" action="../php/sendCSV.php?country=' + currentChecklistCountry + '"></form>');
$('body').append(form);
form.submit();
form.remove();
}
else checklistCountryButton.classList.add("needsAttention");
}
function openChecklistPage() {
if (!currentChecklistCountry) {
checklistCountryButton.innerHTML = "Select Country";
checklistCountryButton.classList.add("needsAttention");
return;
}
if (gNumDays == undefined) gNumDays = 12;
vars = "?country=" + currentChecklistCountry;
vars += "&num_days=" + gNumDays;
vars += "&line_nos=" + lineNumbers.checked;
vars += "&left_check=" + leftCheck.checked;
vars += "&endemics=" + showEndemics.checked;
vars += "&sci_names=" + !sciNames.checked;
vars += "&italics=" + !italics.checked;
window.open( '../php/makePDF.php' + vars, '_blank' );
}
So the getCSVText() methods downloads a file using a temporary form appended and then immediately removed, and openChecklistPage() successfully opens another browser window with a pdf file. The pdf file is never saved on the server. The CSV file is already stored there and just retrieved. Perhaps you can modify the code for your purposes.

Laravel uploading file using Ajax

I'm using the Laravel framework. I have a form of adding a new item to the database and in that form the user can also drag and drop a file. Then, a progress bar is displayed until it's completed, using Ajax for uploading the file to the server.
Once submitting that form, I run the addItem function in a controller and I want to do/check:
That the file is already hosted in the server (successful upload)
If the file is hosted in the server, how do I find it? (I gave it a random name)
If the user chose not to submit the form, I wish to erase that file from the server, so I won't have files that are not connected to any item on my database
Can you suggest any ideas on how to complete these tasks?
To send files by AJAX you need to use FormData which is a class of XMLHttpRequest2, it doesn't work with IE<10.
You also need AJAX2 to show progress.
SAMPLE SUBMIT FORM WITH FILES AND PROGRESS VIA AJAX:
Here I have made an example. In this example the form sends the data and files via AJAX using FormData and show the upload progress percentage in #progress using the progress event. Obviously it is a sample and it could be changed to adapt it.
$('form').submit(function(e) { // capture submit
e.preventDefault();
var fd = new FormData(this); // XXX: Neex AJAX2
// You could show a loading image for example...
$.ajax({
url: $(this).attr('action'),
xhr: function() { // custom xhr (is the best)
var xhr = new XMLHttpRequest();
var total = 0;
// Get the total size of files
$.each(document.getElementById('files').files, function(i, file) {
total += file.size;
});
// Called when upload progress changes. xhr2
xhr.upload.addEventListener("progress", function(evt) {
// show progress like example
var loaded = (evt.loaded / total).toFixed(2)*100; // percent
$('#progress').text('Uploading... ' + loaded + '%' );
}, false);
return xhr;
},
type: 'post',
processData: false,
contentType: false,
data: fd,
success: function(data) {
// do something...
alert('uploaded');
}
});
});
See how works!!: http://jsfiddle.net/0xnqy7du/3/
LARAVEL:
In laravel you can get the file with Input::file, move to another location and save in the database if you need it:
Input::file('photo')->move($destinationPath, $fileName);
// Sample save in the database
$image = new Image();
$image->path = $destinationPath . $fileName;
$image->name = 'Webpage logo';
$image->save();

want to get the file name and its path which was uploaded using jquery plugin

I used a jquery plugin to upload a files into a specified folder.upload was done properly,What i want is to get the the name of the file and its path to store it in a database.I don,t know which variable i have to use get that .Here is my plugin,
$(function () {
// Change this to the location of your server-side upload handler:
var url = 'test_upload_charity.php';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
And my test_upload_charity.php is
<?php
error_reporting(E_ALL | E_STRICT);
include "UploadHandler_charity.php";
$uploadhandlerobj=new UploadHandler_charity();
$filename_uploaded=$uploadhandlerobj->get_file_name();
$file = fopen("test123456.txt","w");
echo fwrite($file,"The file is ".$filename_uploaded);
fclose($file);
?>
The UploadHandler_charity.php is
https://github.com/blueimp/jQuery-File-Upload
In that link it was inside server folder
Try to use:
$_FILES["file"]["name"]
I cannot find an official function in your library to get it.
If that does not work you can try printing the whole _FILES array:
print_r($_FILES);
and see if you can find the needed data in the array.

ajaxFileUpload on xhr.setRequestHeader is not a function

In my footer.php I have this code which i needed for my api references
<script type="text/javascript">
/** Override ajaxSend so we can add the api key for every call **/
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
});
</script>
It works fine in my project without any error but when I started working on file upload and I'm using ajaxfileupload to upload file, I got this error whenever i upload the file.
TypeError: xhr.setRequestHeader is not a function
xhr.setRequestHeader("KEY", "123456POIUMSSD");
Here is my ajaxfileuplod program code:
<script type="text/javascript">
$(document).ready(function() {
var DocsMasterView = Backbone.View.extend({
el: $("#documents-info"),
initialize: function () {
},
events: {
'submit' : 'test'
},
test: function (e) {
e.preventDefault();
var request = $.ajaxFileUpload({
url :'./crew-upload-file',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
request.abort();
return false;
}
});
var x = new DocsMasterView();
});
</script>
Can anyone here fix my problem. Any suggestion/advice in order to solve my problem.
As I understand from your comments, setRequestHeaders works fine with regular ajax calls. At the same time it is not available when ajaxFileUpload is used. Most likely that is because transport method does not allow to set headers (for instance, in case when iframe is used to emulate upload of files in ajax style) . So, possible solution is to place a key into your form data:
$(document).ajaxSend(function(e, xhr, options)
{
if(xhr.setRequestHeader) {
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
else
options.data["<?php echo $this->config->item('rest_key_name');?>"] = "<?php echo $this->session->userdata('api_key')?>";
});
Note: I'm not sure if options.data is a correct statement, just do not remember structure of options object. If proposed code does not work - try to do console.log(options) and how
to get an object with data that should be posted (it might be something like options.formData, I just do not remember exactly)
And on server side you will just need to check for key in headers or form data.

Trying to upload a file through jQuery .post() - file input not showing up on back end (using codeigniter)

First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU

Categories