I am trying get use of Ajax file uploader
http://valums.com/ajax-upload/
The doc says:
var uploader = new qq.FileUploader({
// pass the dom node (ex. $(selector)[0] for jQuery users)
element: document.getElementById('file-uploader'),
// path to server-side upload script
action: '/server/upload'
// WHAT IS action:?
});
The element property means what element ID is used as Upload button.
What is action? It must be some sort of handler for uploaded files?
How I can handle uploaded files and where are located?
The doc says
// events
// you can return false to abort submit
onSubmit: function(id, fileName){},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},
I want when upload complete display a list of files somewhere, say in div with ID=list
The short snippet will be highly appreciated and awarded.
I've used File Uploader quite a lot and I think it is the best file uploader out there.
The action is the method (URL) which receives the call from your Ajax client script.
You have to define a DIV in your HTML:
<div id="uploaderFile"></div>
I've used a javascript function to build my uploader around the DIV:
function CreateImageUploader() {
var uploader = new qq.FileUploader({
element: $('#uploaderFile')[0],
template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
'<div class="qq-upload-button ui-button ui-widget ui-corner-all ui-button-text-only ui-state-default">Seleziona il Listino Excel</div>' +
'<ul class="qq-upload-list"></ul>' +
'</div>',
hoverClass: 'ui-state-hover',
focusClass: 'ui-state-focus',
action: 'Home/UploadImage',
allowedExtensions: ['jpg', 'gif'],
params: { },
onSubmit: function(file, ext) {
},
onComplete: function(id, fileName, responseJSON) {
$("#PopupImageUploader").dialog('close');
}
}
});
}
What happens here is you're creating an uploader around this element element: $('#uploaderFile')[0]. I've used the standard template but you can change the appearance.
When you've done that everything is pretty much setup on the client-side.
On the server side (it depends what you're using) you have to intercept and read the file and persist it.
I use ASP.NET MVC. You can find my action here and here
Your server-side code will manage to persist the file where you want and will return infos to the client script.
Personally I return json data which I manage with the event onComplete to: close a dialog (like in the example); show a message etc etc etc.
If you want to pass parameters back to the client on the server side you can return a JSON object. I would do something like this:
return ("{success:true, newfilename: '" + newFileName + "'}");
I reckon that in PHP could be something like this:
echo {success:true, newfilename: '" + newFileName + "'}";
Forgive me if there are mistakes in that but I've never written a single PHP line in my whole life ;-)
the client side now can check the JSON object like this:
onComplete: function(id, fileName, responseJSON) {
alert(responseJSON.newfilename);
}
As you can see I pass back the result of the action: success:true or success:false so I can show a warning to the user:
onComplete: function(id, fileName, responseJSON) {
if (responseJSON.success)
{
alert(responseJSON.newfilename);
}
else {
alert("something wrong happened");
}
}
How I can handle uploaded files and where are located?
This depends on your webserver and backend language. In PHP have a look at the $_FILES array.
What is action? It must be some sort of handler for uploaded files?
The URL the form used to upload the file is submitted to.
What is action? It must be some sort of handler for uploaded files?
Yes, same as for the HTML <form> element's attribute.
How I can handle uploaded files
With a server side script written in your server side language of preference.
and where are located?
Probably as a stream to STDIN. The forms library you use with the aforementioned server side language have methods to extract it automatically.
Related
This question is more of how to logically approach this obstacle instead of correcting code.
I have a very large application which is based on a 'Wizard'. Users input their data, continue on, data is saved, etc.
In the end, the user needs to be able to print a PDF of all this collected data from the Wizard process. I don't want to use the data from the database, but capture the data 'currently' in the Wizard.
I've been able to make a hidden form on the page, jquery creates new hidden inputs with small strings of data. Then when the user clicks 'print' the data is sent via post and is used in the pdf... but I need a way to send large amounts of data.
So, to make my life easier, is it possible to send an entire specified div or table to TCPDF to use as an htmlcell ?
P.S. jQuery, HTML, PHP are at my disposal.
I don't know this methode is correct or not.But it works..Send data through ajax as an array to server
Create pdf . Save pdf server side folder and open the pdf in another window
**// Post data to server
$.ajax({
type:"POST",
url:"//path",
data:"&arrDataArray="+arrDataArray,
success:function(Results){
//if preview then open the pdf in a new tab
if(Results=='PREVIEW'){
highLightPrintSettingsTab(strCurrentTab);
$(".busyLoading").hide();
window.open("../pdffiles/example.pdf","_blank");
}
}
});
Here is what I ended up doing. Works like charm.
function submitData(url, method, data) {
var $form = $('<form></form>')
.attr('action', url)
.attr('method', method)
.attr('target', '_blank')
.appendTo('body');
for (var i in data) {
if (!data.hasOwnProperty(i)) continue;
$('<input type="hidden"/>')
.attr('name', i)
.val(JSON.stringify(data[i]))
.appendTo($form);
}
$form.submit();
}
});
Where 'data' will be the array(s) you wish to send to wherever, in my case the controller for tcpdf. {multi, data} for plural.
I've read many posts that due to security risks you cannot upload to your server with an image from your folder as javascript isnt allowed such access. However, I have a situation where i have an svg image on a web site that I convert to a png whilst on the website. But, I wish to send the converted image to my server.
Will I encounter the same problems as if I were uploading from my documents?
I tried to make an example of jsfiddle but it seems it doesnt accept document.write very well, so here's sort of a work-around:
DEMO: jsfiddle
Ideally we would have a button defined as so:
<button id="image" onClick="image()">Convert & Send</button>
Then have the code that does the conversion within a function along with the ajax
function image() {
//conversion code & ajax
}
So in conclusion I would just like to know if this is possible if not, i would be grateful if you could show an alternative way, whether it may include a combination of php.
thanks in advance
It seems as though the fiddle isnt loading heres the snippet: of the conversion
function image () {
var svg = document.getElementById("svg-container").innerHTML.trim();
var canvas = document.getElementById('svg-canvas');
canvg(canvas, svg, { renderCallback: function () {
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
}
});
I'm not sure about what your question is, but indeed, you can use a combination of Ajax + PHP to upload your image.
The client would POST an encoded image (e.g. encoded in Base64) using ajax (using jQuery.post, for example), while the PHP would receive the image and store it (after decoding it) in your server.
For an example of the process, check this question, where a specific case of a canvas is discussed. I think your SVG conversion could work in a similar way.
PS: For some reason, I couldn't load your Fiddle.
EDIT:
So both Ajax & PHP are written on the front end to send the image to
my server/database (ruby on rails). Is that correct?
No. Only Javascript (with Ajax) is used in the client. PHP would be the server part of the process, so in your case it would not be used as you are already using Ruby on Rails. In other words:
The client (browser) uses Javascript (maybe JQuery) to POST the image data (in your snippet, img) to the server (more info here).
The server (a PHP, ASPX or Ruby script [among others]) gets the POSTed data and saves the picture on disk (some info here).
If you can use PHP (in the server) for the specific process of saving the image, you can use the question I linked before as a guide.
Yes Of Course Their are ways:
I know 2:
1-(This One I know it works on chrome and Firefox but don't know IE):
First Get The Base 64 Data Of An Image In Canvas:
<canvas id="Canv" ....(Other Attributes)>
Your Browser does not support the canvas element :(
</canvas>
<button type="button" OnClick="Image()">Transform and Save</button>
<script type="text/javascript>
var can =document.getElementById('Can');
var ctx = can.getContext("2d");
//do something with ctx
function image(){
//You Should check the real format using img.src
var data = can.toDataURL("image/png");
var array = data.split(".");
var Base64Data = array[1];
//Now step 2 :Sent it to PHP
//Check for Browser compatibly
var ajx = new XmlHttpRequest()
ajx.onreadystatechange=function()
{
if (ajx.readyState==4 && ajx.status==200)
{
if(ajx.ResponseText == "Err"){//if the paged returned error
alert("An error Has Occurred");
return;
}//if not
alert("Saved Succesufuly");
}
}
ajx.open("GET","Save.php?q=" + Base64Data , true);
}
</script>
Step3: Interprete it With PHP
<?PHP
if(isset($_GET['q] And !Empty($_GET['q'])){
try {
$Data = $_GET['q'];
$hndl = fopen("Saved/Pic1.jpg" , "w");
fwrite($hndl , $Data);
fclose($hndl);
}catch(Exception $err){
echo "Err";
}
}else {
echo "Err";
}
?>
Yeap And That it.:D
You Could also loop throught each file in that directory and create a load button that get the Base64 Value And the first stuffs and out it into canvas using pucontent method of canvas element object
I am modifying a script to make up a firefox extension for my website. The original script ( chrome extension) stores data into a local websql database. I want it rather to send the three variable to a php file using this format
http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title
The part of Js that is normally sending the data is the following
// post credentials to background
chrome.extension.sendRequest({
action: 'queryDatabase',
crud: 'create',
record: [
window.location.href,
window.location.hostname,
title,
article
]
});
I would be glad if any one can lead me through the modification of this code
You can use jQuery's ajax() method to accomplish this:
// post credentials to http://mysite.com/receiver.php
jQuery.ajax({
url: "http://mysite.com/receiver.php",
type: 'GET',
data: {
id: "href",
title: "hostname",
article: "article"
}
}).success(function ( data ) {
alert("completed successfully");
}).error(function ( data ) {
alert("there was an error");
});
http://api.jquery.com/jQuery.ajax/
example of the image/PHP solution. The jQuery Ajax solution listed is good if you need to know what was returned (I use it on things like http://jsErrLog.appspot.com and it's a great solution), the image is good if you just want to throw something over the fence and move on. Both as non-blocking
in the HTML page the Javascript would need to trigger a call that requests an image:
<script>
databaseImage = new Image();
databaseImage.src = "http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title";
</script>
and the PHP page that it calls would, after storing the data, would need to return an image (cleaner than sending back something inappropriate) -
<?
$im = file_get_contents('{path to your 1px .gif}');
header('content-type: image/gif');
echo $im;
?>
Ok guys im a bit stuck here. I usually use jquery to do this but i found out it cant be done with jquery so im doing it this way ok so this is my code
var url = ("upload.php?loc="+uplocation);
var xhr = new XMLHttpRequest();
if(xhr.upload){ // check if upload property exists
xhr.open("POST", url, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
And all it does is sends a file to a php page, but the php page doesn't upload the image which isn't what i want, so is their anyway of returning all the contents thats displayed on the page
if it was jquery i would do something like this
$.ajax({
type: "POST",
url: 'json/submitsongs.php',
data: loca,
success: function(data){
alert(data);
}
});
so my question is how to do return what ever is echoed on the php page and alert it(for debugging reasons).
thanks for your help
You would add an event listener for whatever event you desired (load, error, progress, etc). So in your case you would use the 'load' event which signifies that the file has finished loading:
xhr.addEventListener('load', onComplete, false);
The onComplete is your callback function which has the event as a parameter. This event contains the response text:
function onComplete(event) {
alert(event.target.responseText);
}
As of today, u can not upload async using Ajax.
Either use Iframes (like Google) or some nifty Flash (or Java) upload app.
Not sure, but might be HTML5 has a solution for that, but it won't be cross browser.
i'm trying to read the filesize of a file while uploading it this way
1 . start an $.ajax(); request to start a server to server downloading of file (i'm using php fopen + stream_copy_to_stream );
2 . start a second $a.ajax(); request each tot time and try to read the current filesize till the end of download process;
unfortunely this don't work as expected.
both the requests are made correctly but the filesize is read only after the file is fully transfered. so i get all the alert message at the end of the process instead of meanwhile
i guess i'm doing something that can't be done? or i'm just missing something?
pseudo code:
var uploadStart = 0;
function startUploadProgressBar(file) {
var file = file;
uploadStart = setInterval(function() {
$.ajax({
data: 'uploadProgress=1&file=' + file,
success: function(json) {
alert(json.filesize)
}
});
},
1000);
}
$('#submit').click(function() {
var file = somevar;
startUploadProgressBar(file);
$.ajax({
success: function(json) {
clearInterval(uploadStart);
}
});
return false;
});
Just for uploading files via ajax, you can consider using the jQuery forms plugin. It supports progress bars, as far as I know.
If you want to stick to your method, read through the comments of the function's manual page in the PHP manual. There are alternatives that can be modified outputting states of the transfer.
Why not just have the PHP page return the size of the file itself using filesize()? That way you don't need to poll repeatedly.