riccardo castagna - 2010-04-02 08:46:00
I know it's impossible to upload a file to a server from a form using ajax. Everywhere the best solution is the hidden iframe, but I don't like this solution very much.
I found an ajax script (by Mr. Benjamin Schirmer) on google code ( http://code.google.com/intl/it/apis/desktop/articles/e9.html ) that can load a text file on a server using ajax without hidden iframe.
My idea is to convert an image file into base64 using javascript (the client will do it) and then upload this file on the server in text format. After decoding the file with PHP.
I know there is also the problem to solve about form enctype="multipart/form-data"
to give the client the possibility to choose the file to upload. The ajax code (I like prototype) to get the form field doesn't work with the input type="file".
Any of you more experienced than me in Ajax (who wants to go mad with me...) believes that is possible to develop something about in pure ajax ?
Here is the starting ajax code (by Mr. Benjamin Schirmer) to upload a text file to a server:
function loadFile( filename ) {
var fp = system.filesystem.OpenTextFile( filename, 1, false);
var s = fp.ReadAll();
fp.close();
return s;
}
function uploadFile( url, filename ) {
var boundaryString = "AaBbCcX30";
var boundary = "--"+boundaryString;
var fileData = loadFile( filename );
var postContent = "\r\n"+boundary+"\r\n"+
"Content-Disposition: form-data; name=\"comment\"\r\n"+
"\r\n"+
"Comment is another input\r\n"+
boundary+"\r\n"+
"Content-Disposition: file; name=\"uploadedfile\"; filename=\"test.txt\"\r\n"+
"Content-Type: text/plain\r\n"+
"\r\n"+
"%FILECONTENT%\r\n"+
boundary+"\r\n";
postContent = postContent.replace("%FILECONTENT%", fileData);
gadget.debug.trace( postContent );
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundaryString);
req.onreadystatechange = function() {
gadget.debug.trace("ReadyState: "+req.readyState);
if (req.readyState == 4) {
if (req.status == 200) {
gadget.debug.trace( req.responseText );
}
}
};
req.send(postContent);
}