PHP Classes

AJAX PHP UPLOAD FILE TO A SERVER

Recommend this page to a friend!

      Top level forums  >  PHP Specialists  >  General  >  AJAX PHP UPLOAD FILE TO A SERVER  
Subject:AJAX PHP UPLOAD FILE TO A SERVER
Summary:Hidden iframe Vs. Something else (Pure Ajax - Prototype )
Messages:12
Author:riccardo castagna
Date:2010-04-02 08:46:00
Update:2010-04-03 21:52:28
 

  1. AJAX PHP UPLOAD FILE TO A SERVER   Reply   Report abuse  
Picture of riccardo castagna 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);
}


There are 11 replies in this thread, which are not being displayed.
Browsing this forum thread replies is available only to premium subscribers.


Go to the premium subscriptions page to learn how to become a premium subscriber and have full access to this forum.