使用 HTTP/1.1 PUT 方法异步上传文件(AJAX),为什么不呢?
可以通过“普通网络浏览器”通过 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);
?>
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);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您上传文件时,您必须上传该文件。告诉服务器本地文件名是什么......还不够。
JavaScript 在标准安全上下文中的 Web 浏览器中运行,无权从用户硬盘读取文件中的数据。
由于无法获取数据,因此无法上传。
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.
具体针对您的解决方案,主要是因为并非所有浏览器(尤其是较旧的浏览器)都支持
PUT
方法(动词),因此该解决方案并不适合所有人。该主题之前也出现过,虽然不完全相同,但一些答案是
PUT
和DELETE
不起作用的示例。$.ajax()
的文档也提到了这一点 :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
andDELETE
don't work.The documentation for
$.ajax()
mentions this as well: