上传文件返回提取码
There’s a task that should be simple, but sometimes it leads to hours of research on the Web: uploading files to the server.
有一项任务应该很简单,但有时会导致在Web上进行大量研究:将文件上传到服务器。
In this tutorial I explain you how to do so using fetch
.
在本教程中,我将向您解释如何使用fetch
。
Given a form with a file input field:
给定一个带有文件输入字段的表单:
<input type="file" id="fileUpload" />
We attach a change
event handler on it:
我们在其上附加一个change
事件处理程序:
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event)
})
and we manage the bulk of our logic in the handleImageUpload()
function:
并且我们在handleImageUpload()
函数中管理大部分逻辑:
const handleImageUpload = event => {
const files = event.target.files
const formData = new FormData()
formData.append('myFile', files[0])
fetch('/saveImage', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.error(error)
})
}
In this example we POST to the /saveImage
endpoint.
在此示例中,我们发布到/saveImage
端点。
We initialize a new FormData
object and we assign it to the formData
variable, and we append there the uploaded file. If we have more than one file input element, we’d have more than one append()
call.
我们初始化一个新的FormData
对象,并将其分配给formData
变量,然后在此附加上载的文件。 如果我们有多个文件输入元素,那么将有多个调用append()
。
The data
variable inside the second then()
will contain the JSON parsed return data. I’m assuming your server will give you JSON as a response.
第二个then()
内部的data
变量将包含JSON解析的返回数据。 我假设您的服务器将给您JSON作为响应。
How to handle images uploaded server-side is a different topic, one I’ll write about tomorrow.
如何处理在服务器端上传的图像是另一个主题,我明天将写一个主题。
上传文件返回提取码