You are viewing a plain text version of this content. The canonical link for it is here.
Posted to modperl@perl.apache.org by Michael Wichmann <ma...@web.de> on 2010/07/28 12:26:12 UTC

File transfer with Apache2::Upload and XMLHttpRequest

 I tried to switch from the 'common' way to send a file to the server, which is in my case:

a) define a form with an file-input-element:

<form method="post" action="gallery?action=upload_image" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="Submit" />
</form>

b) define mod_perl code, that saves the file-data inside a handler, something like:

    my $apr = Apache2::Request->new($r);
    my $upload = $apr->upload('file');
    ....

That works fine as it is easy to work with $upload and save the data.
But I really can not figure out how to handle the XHR-Approach on the server-side because now, of cause, the 'file' param is missing.

The JS client side code is (where 'file' is a HTML5 File-Object):

var xhr = new XMLHttpRequest();
xhr.open("POST", url + "?filename=" + encodeURIComponent(file.name), true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(file);

Any idea how now the server side part has to look like now?

Thanks, Michael

Re: File transfer with Apache2::Upload and XMLHttpRequest

Posted by André Warnier <aw...@ice-sa.com>.
Michael Wichmann wrote:
>  I tried to switch from the 'common' way to send a file to the server, which is in my case:
> 
> a) define a form with an file-input-element:
> 
> <form method="post" action="gallery?action=upload_image" enctype="multipart/form-data">
>     <input type="file" name="file"/>
>     <input type="submit" value="Submit" />
> </form>
> 
> b) define mod_perl code, that saves the file-data inside a handler, something like:
> 
>     my $apr = Apache2::Request->new($r);
>     my $upload = $apr->upload('file');
>     ....
> 
> That works fine as it is easy to work with $upload and save the data.
> But I really can not figure out how to handle the XHR-Approach on the server-side because now, of cause, the 'file' param is missing.
> 
> The JS client side code is (where 'file' is a HTML5 File-Object):
> 
> var xhr = new XMLHttpRequest();
> xhr.open("POST", url + "?filename=" + encodeURIComponent(file.name), true);
> xhr.setRequestHeader("Content-Type", "multipart/form-data");
> xhr.send(file);
> 
> Any idea how now the server side part has to look like now?
> 
No, because your way of sending the file to the server does not match the Content-Type.
A multipart/form-data content type implies that the body of your POST should look like a 
MIME message, where each part has its own set of headers and a body.
Here you are apparently just sending the file, as is.
It is a bit more complex than that.

Maybe search in Google for "ajax file upload" or something of the kind, to find a 
javascript library that would do that ?