我想使用JavaScript创建一个上传器。有人可以帮助我学习如何使用JavaScript上传文件吗?
我想使用JavaScript创建一个上传器。有人可以帮助我学习如何使用JavaScript上传文件吗?
你可以像这样使用HTML5文件类型:
<input type="file" id="myFile">
您的文件将具有价值:
var myUploadedFile = document.getElementById("myFile").files[0];
更多信息请参见:https://www.w3schools.com/jsref/dom_obj_fileupload.asp,并在此处查看示例:https://www.script-tutorials.com/pure-html5-file-upload/。XMLHttpRequest
和 FormData
上传文件。下面的示例展示了如何上传新选择的文件。<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>
HTML部分:
<form enctype = "multipart/form-data" onsubmit="return false;" >
<input id="file" type="file" name="static_file" />
<button id="upload-button" onclick="uploadFile(this.form)"> Upload </button>
</form>
JavaScript 部分:
function uploadFile(form){
const formData = new FormData(form);
var oOutput = document.getElementById("static_file_response")
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload_static_file", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
console.log(oReq.response)
} else {
oOutput.innerHTML = "Error occurred when trying to upload your file.<br \/>";
}
};
oOutput.innerHTML = "Sending file!";
console.log("Sending file!")
oReq.send(formData);
}