Javascript 如何在没有jQuery和支持IE6-9的情况下异步上传文件?
我有一个简单的上传文件的表单,可以很好地同步工作:Javascript 如何在没有jQuery和支持IE6-9的情况下异步上传文件?,javascript,asynchronous,file-upload,internet-explorer-6,Javascript,Asynchronous,File Upload,Internet Explorer 6,我有一个简单的上传文件的表单,可以很好地同步工作: <form id="uploadForm" action="/upload" method="post" encType="multipart/form-data"> <input type="file" id="file" name="file" accept=".csv" /> <input type="text" name="comment" /> <button type="subm
<form id="uploadForm" action="/upload" method="post" encType="multipart/form-data">
<input type="file" id="file" name="file" accept=".csv" />
<input type="text" name="comment" />
<button type="submit">Upload</button>
</form>
但是,发送FormData
、Blob
s、File
s或ArrayBuffer
s仅在IE10+中受支持,我需要一个向后兼容的解决方案(不使用jQuery)
有很多答案,但到目前为止我读到的所有答案都使用jQuery或使用我上面描述的现代XMLHttpRequest方法
我正在使用React,不使用jQuery提供的任何其他功能,因此我希望通过使用vanilla JS解决此问题来减小我的页面下载大小。最古老的方法是通过向
元素添加target=“”
,使
目标成为隐藏的
元素。在JavaScript中调用form.submit()
时,它将在目标
中加载响应:
<form id="uploadForm" action="/upload" method="post" encType="multipart/form-data" target="asyncFrame">
<iframe id="asyncFrame" name="asyncFrame" height="0" width="0" frameborder="0"></iframe>
<input type="file" id="file" name="file" accept=".csv" />
<input type="text" name="comment" />
<button type="submit">Upload</button>
</form>
<script>
var iframe = document.getElementById('asyncFrame');
function handleLoad() {
console.log('response:', iframe.contentWindow.document.body.innerText);
}
iframe.addEventListener('load', handleLoad);
</script>
上载
var iframe=document.getElementById('asyncFrame');
函数handleLoad(){
log('response:',iframe.contentWindow.document.body.innerText);
}
iframe.addEventListener(“加载”,手动加载);
这种方法最尴尬的地方是,没有办法获取响应的状态代码,也没有标准方法(据我所知)来确定请求是否失败。您必须检查响应正文(
iframe.contentWindow.document.body.innerText
)以确定是否存在错误(如果您正在向自己的服务器发布,幸运的是,您可以确保响应正文包含足够的信息,但如果它是第三方服务器,您可能运气不佳).@黑曜石在这里回答声誉问题。我问这个问题是因为我们应该得到一个不使用jQuery的顶级答案。浏览jQuery的答案很糟糕。@Andy——不过你已经有了这个问题的答案;如果您的问题事先解决了,为什么要问这个问题?您好,您应该了解jQuery在上传文件的封面下实际做了什么。想法是创建formData,在formData中附加文件,然后将ajax(XMLHttpRequest)发送到服务器以上载文件,或者您可以将其包装在iframe中,然后从iframe发布formData以上载您的文件。@Andy我相信我的回答不涉及任何类型的jQuery。如何解决“没有jQuery如何执行x”的问题与“如何使用jquery执行x”问题完全相同????
<form id="uploadForm" action="/upload" method="post" encType="multipart/form-data" target="asyncFrame">
<iframe id="asyncFrame" name="asyncFrame" height="0" width="0" frameborder="0"></iframe>
<input type="file" id="file" name="file" accept=".csv" />
<input type="text" name="comment" />
<button type="submit">Upload</button>
</form>
<script>
var iframe = document.getElementById('asyncFrame');
function handleLoad() {
console.log('response:', iframe.contentWindow.document.body.innerText);
}
iframe.addEventListener('load', handleLoad);
</script>