formdata对象
The FormData
object is used to hold form values in a key-value pairs data structure.
FormData
对象用于在键值对数据结构中保存表单值。
You create an empty FormData
object in this way:
您可以通过以下方式创建一个空的FormData
对象:
const fd = new FormData()
Once you have the item you can call one of its methods:
获得项目后,可以调用其方法之一:
append()
to add a value to the object, with the specified key. If the key already exists, the value is added to that key, without eliminating the first oneappend()
使用指定的键将值添加到对象。 如果键已经存在,则将值添加到该键,而不会消除第一个键delete()
deletes a key value pairdelete()
删除键值对entries()
gives an Iterator object you can loop to list the key value pairs hostedentries()
提供了一个Iterator对象,您可以对其进行循环以列出托管的键值对get()
get the value associated with a key. If more than one value was appended, it returns the first oneget()
获取与键关联的值。 如果附加了多个值,则返回第一个getAll()
get all the values associated with a keygetAll()
获取与键关联的所有值has()
returns true if there’s a key如果有键,
has()
返回truekeys()
gives an Iterator object you can loop to list the keys hostedkeys()
提供了一个Iterator对象,您可以对其进行循环以列出托管的键set()
to add a value to the object, with the specified key. If the key already exists, the value is replacedset()
使用指定的键将值添加到对象。 如果键已经存在,则替换该值values()
gives an Iterator object you can loop to list the values hostedvalues()
提供了一个Iterator对象,您可以对其进行循环以列出托管的值
The FormData object is part of the XMLHttpRequest 2 spec. It’s available in all the modern browsers but keep in mind that IE versions prior to 10 do not support it.
FormData对象是XMLHttpRequest 2规范的一部分。 它在所有现代浏览器中都可用,但是请记住,低于10的IE版本不支持它。
Here is one example of using FormData to send the content of a file using an XHR connection:
这是一个使用FormData通过XHR连接发送文件内容的示例:
<input type="file" id="fileUpload" />
const sendFile = file => {
const uri = '/saveImage'
const xhr = new XMLHttpRequest()
const fd = new FormData()
xhr.open('POST', uri, true)
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
const imageName = xhr.responseText
//do what you want with the image name returned
//e.g update the interface
}
}
fd.append('myFile', file)
xhr.send(fd)
}
const handleImageUpload = event => {
const files = event.target.files
sendFile(files[0])
}
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event)
})
This snippet instead can be used to send multiple files:
该代码段可用于发送多个文件:
<input type="file" id="fileUpload" multiple />
const sendFiles = files => {
const uri = '/saveImage'
const xhr = new XMLHttpRequest()
const fd = new FormData()
xhr.open('POST', uri, true)
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
const imageName = xhr.responseText
//do what you want with the image name returned
//e.g update the interface
}
}
for (let i = 0; i < files.length; i++) {
fd.append(files[i].name, files[i])
}
xhr.send(fd)
}
const handleImageUpload = event => {
sendFiles(event.target.files)
}
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event)
})
formdata对象