Code前端首页关于Code前端联系我们

FormData 对象

terry 2年前 (2023-09-07) 阅读数 236 #Html5

了解 FormData 对象是什么以及如何使用它。

FormData对象

FormData 对象用于将表单值存储在键值对数据结构中。

您可以像这样创建一个空的 FormData 对象:

/**
* 前端教程网
* https://www.pipipi.net/
*/
const fd = new FormData()

当您有孩子时,您可以通过以下方式之一致电:

  • append() 使用指定的键将值附加到对象。如果键已存在,则将值添加到键中,而不删除第一个键
  • delete() 删除键值对
  • entries() 返回一个迭代器对象,您可以循环遍历列表 Out-resident key -值对
  • get() 获取与键关联的值。如果添加多个值,则返回第一个值
  • getAll() 获取与该键关联的所有值
  • has() 如果是键名则返回 true
  • keys() 返回一个对象迭代器,您可以迭代指定键的列表
  • set() 使用指定的键向对象添加一个值。如果键已经存在,则值将被替换
  • values() 返回一个迭代器对象,您可以迭代该对象以列出列出的值

FormData 对象是 XMLHttpRequest 2 定义的一部分。 可在所有现代浏览器中使用,但请注意,10年前的IE版本不支持它。

以下是使用 XHR 连接通过 FormData 发送文件内容的示例:

<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)
})

此代码可用于发送多个文件:

<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)
})

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门