如何使用javascript上传文件? [英] How to upload a file using javascript?
本文介绍了如何使用javascript上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用js创建一个上传器.谁能帮助我如何使用JavaScript上传文件?
I want to create an uploader with js. Can anyone help me how to upload a file using javascript?
推荐答案
您可以使用XMLHttpRequest
和FormData
上传文件.下面的示例显示了如何上传新选择的文件.
You can upload files with XMLHttpRequest
and FormData
. The example below shows how to upload a newly selected file(s).
<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {
const fd = new FormData();
// add all selected files
e.target.files.forEach((file) => {
fd.append(e.target.name, file, file.name);
});
// create the request
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
// we done!
}
};
// path to server would be where you'd normally post the form to
xhr.open('POST', '/path/to/server', true);
xhr.send(fd);
});
</script>
免责声明,我是 FilePond 的作者,这与上传方式非常相似也是
Disclaimer, I'm the author of FilePond and this is very similar to how it does uploading as well.
这篇关于如何使用javascript上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文