Javascript 使用 Ajax XmlHttpRequest 上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6211145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload File With Ajax XmlHttpRequest
提问by Sedat Ba?ar
Hi i am trying to send file with xmlhttprequest with this code.
嗨,我正在尝试使用此代码发送带有 xmlhttprequest 的文件。
<script>
var url= "http://localhost:80/....";
$(document).ready(function(){
document.getElementById('upload').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if ( xhr.upload ) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', url, true);
xhr.setRequestHeader("Content-Type","multipart/form-data");
xhr.send(file);
}, false);
});
</script>
but i got this error : the request was rejected because no multipart boundary was found help me pls..
但我收到此错误:请求被拒绝,因为未找到多部分边界请帮助我..
回答by timdream
- There is no such thing as
xhr.file = file;
; the file object is not supposed to be attached this way. xhr.send(file)
doesn't send the file. You have to use theFormData
object to wrap the file into amultipart/form-data
post data object:var formData = new FormData(); formData.append("thefile", file); xhr.send(formData);
- 没有这样的事情
xhr.file = file;
;文件对象不应该以这种方式附加。 xhr.send(file)
不发送文件。您必须使用该FormData
对象将文件包装到multipart/form-data
发布数据对象中:var formData = new FormData(); formData.append("thefile", file); xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
之后,可以访问该文件$_FILES['thefile']
(如果您使用的是 PHP)。
Remember, MDCand Mozilla Hack demosare your best friends.
请记住,MDC和Mozilla Hack 演示是您最好的朋友。
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
编辑:上面的 (2) 不正确。它确实发送文件,但它会将其作为原始发布数据发送。这意味着您必须自己在服务器上解析它(这通常是不可能的,取决于服务器配置)。在此处阅读如何在 PHP 中获取原始帖子数据。