使用HTTP / 1.1 PUT方法异步上传文件(AJAX),为什么不呢?

时间:2010-10-03 11:21:31

标签: ajax file-upload asynchronous upload asyncfileupload

可以通过“普通网络浏览器”通过PUT方法上传文件,甚至是二进制文本或文本。 为什么很多人只是说,这是不可能的?

使用jQuery和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: ");
            }
        });     
    });
});

在服务器端,只需读取STDIN流,如

<?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);
?>

2 个答案:

答案 0 :(得分:0)

具体来说,对于您的解决方案,主要是因为所有浏览器都不支持PUT方法(动词),特别是较旧的浏览器,因此此解决方案不适用于所有人。

The topic has come up previously as well虽然不完全相同,但有些答案是PUTDELETE不起作用的示例。

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

  

<强>型
  默认值:'GET'
  要求的类型(“POST”或“GET”),默认为“GET”。

     

注意:此处也可以使用其他HTTP请求方法,例如PUT和DELETE,但并非所有浏览器都支持它们。

答案 1 :(得分:0)

{file: filename}

上传文件时,您必须上传文件。告诉服务器本地文件名是什么......是不够的。

JavaScript在标准安全上下文中的Web浏览器中运行,无权从用户的硬盘读取文件中的数据。

由于您无法获取数据,因此无法上传。