views:

68

answers:

2

Uploading files via PUT method, even binary or text, via a "normal web browser" is possible. Why many people are just saying, that is not possible ?

Sample code with jQuery and PHP.

$(document).ready(function() {
    $("#uploadbutton").click(function() {
        var filename = $("#file").val();
        $.ajax({ 
        type: "PUT",
        url: "addFile.do",
           enctype: 'multipart/form-data',
           data: {file: filename},
          success: function(){
               alert( "Data Uploaded: ");
            }
        });     
    });
});

On the server side just read the STDIN stream like

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>
A: 

For your solution specifically, mainly because the PUT method (verb) is not supported by all browsers, especially older ones, so this solution won't work for everyone.

The topic has come up previously as well, though not exactly the same, some answers are examples of where PUT and DELETE don't work.

The documentation for $.ajax() mentions this as well:

type
Default: 'GET'
The type of request to make ("POST" or "GET"), default is "GET".

Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Nick Craver
A: 
{file: filename}

When you upload a file, you have to upload the file. Telling the server what the local filename is… isn't enough.

JavaScript, running in a web browser in a standard security context, doesn't have access to read the data in the file from the user's hard disk.

Since you can't get the data, you can't upload it.

David Dorward
I think you missed the `PUT` HTTP Verb here, it *does* work, but it's just not as widely supported as you'd need to go this route.
Nick Craver
Isn't that just a *second* hurdle to the problem?
David Dorward
@David - Nope, that's how `PUT` works, to be 100% correct it should be: `addFile.do/filename`, but the problem is support mainly...though yes his current implementation wouldn't work outside of PHP, at least not on any framework I can think of until the URL is corrected. As far as the context of the question though, the problem again is lack of wide-spread support for exactly the OPs approach, rather than limitations preventing it entirely...though there are certainly a dozen good reasons *not* to do it the way the OP has anyway :)
Nick Craver
So by specifying the PUT method, a website can persuade an XHR object to grab data from the user's hard disk and insert it into a PUT request? Does it do anything to warn the user about this first?
David Dorward