formdata多文件上传

In this post, we'll learn about the FormData interface available in modern web browsers as a part of the HTML5 spec.

在本文中,我们将了解HTML5规范中现代Web浏览器中提供的FormData接口。

We'll see examples of using FormData with Ajax, Angular 7, Ionic and React.

我们将看到在Ajax,Angular 7,Ionic和React中使用FormData的示例。

什么是FormData (What's FormData)

FormData is simply a data structure that can be used to store key-value pairs. Just like its name suggests it's designed for holding forms data i.e you can use it with JavaScript to build an object that corresponds to an HTML form. It's mostly useful when you need to send form data to RESTful API endpoints, for example to upload single or multiple files using the XMLHttpRequest interface, the fetch() API or Axios.

FormData只是一个可用于存储键值对的数据结构。 就像它的名字暗示的那样,它是为保存表单数据而设计的,即,您可以将其与JavaScript一起使用以构建与HTML表单相对应的对象。 当您需要将表单数据发送到RESTful API端点时,例如,使用XMLHttpRequest接口, fetch() API或Axios上传单个或多个文件时,它最有用。

You can create a FormData object by instantiating the FormData interface using the new operator as follows:

您可以通过使用new运算符实例化FormData接口来创建FormData对象,如下所示:

const formData = new FormData()

The formData reference refers to an instance of FormData. You can call many methods on the object to add and work with pairs of data. Each pair has a key and value.

formData引用引用FormData的实例。 您可以在对象上调用许多方法来添加和使用数据对。 每对都有一个键和值。

These are the available methods on FormData objects:

这些是FormData对象上可用的方法:

  • append() : used to append a key-value pair to the object. If the key already exists, the value is appended to the original value for that key,

    append() :用于将键值对附加到对象。 如果该键已经存在,则将值附加到该键的原始值,

  • delete(): used to  deletes a key-value pair,

    delete() :用于删除键值对,

  • entries(): returns an Iterator object that you can use to loop through the list the key value pairs in the object,

    entries() :返回一个Iterator对象,您可以使用该对象遍历列表中的键值对,

  • get(): used to return the value for a key. If multiple values are appended, it returns the first value,

    get() :用于返回键的值。 如果附加了多个值,它将返回第一个值,

  • getAll(): used  to return all the values for a specified key,

    getAll() :用于返回指定键的所有值,

  • has(): used to check if there’s a key,

    has() :用于检查是否有钥匙,

  • keys(): returns an Iterator object which you can use to list the available keys in the object,

    keys() :返回一个Iterator对象,您可以使用该对象列出该对象中的可用键,

  • set():  used to add a value to the object, with the specified key. This is going to relace the value if a key already exists,

    set() :用于使用指定的键将值添加到对象。 如果一个键已经存在,这将增加值

  • values():  returns an Iterator object for the values of the FormData object.

    values() :为FormData对象的值返回一个Iterator对象。

Vanilla JavaScript的文件上传示例 (File Upload Example with Vanilla JavaScript)

Let's now see a simple example of file upload using vanilla JavaScript, XMLHttpRequest and FormData.

现在,让我们看一个使用原始JavaScript, XMLHttpRequestFormData上传文件的简单示例。

Navigate to your working folder and create and index.html file with the following content:

导航到您的工作文件夹,并创建包含以下内容的index.html文件:

<!DOCTYPE html>
<html><head><title>Parcel Sandbox</title><meta charset="UTF-8" />
</head><body><div id="app"></div><script src="index.js"></script>
</body></html>

We simply create an HTML document with a <div> identified by the app ID. Next, we include the index.js file using a <script> tag.

我们只需使用app ID标识的<div>创建HTML文档。 接下来,我们使用<script>标记包含index.js文件。

Next, create the index.js file and add following code:

接下来,创建index.js文件并添加以下代码:

document.getElementById("app").innerHTML = `
<h1>File Upload & FormData Example</h1>
<div>
<input type="file" id="fileInput" />
</div>
`;const fileInput = document.querySelector("#fileInput");const uploadFile = file => {console.log("Uploading file...");const API_ENDPOINT = "https://file.io";const request = new XMLHttpRequest();const formData = new FormData();request.open("POST", API_ENDPOINT, true);request.onreadystatechange = () => {if (request.readyState === 4 && request.status === 200) {console.log(request.responseText);}};formData.append("file", file);request.send(formData);
};fileInput.addEventListener("change", event => {const files = event.target.files;uploadFile(files[0]);
});

We first insert an <input type="file" id="fileInput" /> element in our HTML page. This will be used to select the file that we'll be uploading.

我们首先在HTML页面中插入<input type="file" id="fileInput" />元素。 这将用于选择我们将要上传的文件。

Next, we query for  the file input element using the querySelector() method.

接下来,我们使用querySelector()方法查询文件输入元素。

Next, we define the uploadFile() method in which we first declare an  API_ENDPOINT variable that holds the address of our file uploading endpoint. Next, we create an XMLHttpRequest request and an empty FormData object.

接下来,我们定义uploadFile()方法,在该方法中,我们首先声明一个API_ENDPOINT变量,该变量保存文件上传端点的地址。 接下来,我们创建一个XMLHttpRequest请求和一个空的FormData对象。

We use the append method of FormData to append the file, passed as a parameter to the uploadFile() method, to the file key. This will create a key-value pair with file as a key and the content of the passed file as a value.

我们使用FormData的append方法将作为参数传递给uploadFile()方法的文件附加到file密钥。 这将创建一个以file为键的键-值对,并以传递的文件的内容为值。

Next, we send the request using the send() method of XMLHttpRequest and we pass in the FormData object as an argument.

接下来,我们使用XMLHttpRequestsend()方法发送请求,并传入FormData对象作为参数。

After defining the uploadFile() method, we listen for the change event on the <input> element and we call the  uploadFile() method with the selected file as an argument. The file is accessed from event.target.files array.

定义了uploadFile()方法之后,我们侦听<input>元素上的change事件,并以所选文件作为参数调用uploadFile()方法。 该文件是从event.target.files数组访问的。

You can experiment with this example from this code sandbox:

您可以从以下代码沙箱中尝试以下示例:

上载多个文件 (Uploading Multiple Files)

You can easily modify the code above to support multiple file uploading.

您可以轻松修改上面的代码以支持多个文件上传。

First, you need to add the multiple property to the <input> element:

首先,您需要将multiple属性添加到<input>元素:

<input type="file" id="fileInput" multiple />

Now, you'll be able to select multiple files from your drive.

现在,您将能够从驱动器中选择多个文件。

Next, change the uploadFile() method to accept an array of files as an argument and simply loop through the array and append the files to the FormData object:

接下来,更改uploadFile()方法以接受文件数组作为参数,并简单地循环遍历该数组并将文件附加到FormData对象:

const uploadFile = (files) => {console.log("Uploading file...");const API_ENDPOINT = "https://file.io";const request = new XMLHttpRequest();const formData = new FormData();request.open("POST", API_ENDPOINT, true);request.onreadystatechange = () => {if (request.readyState === 4 && request.status === 200) {console.log(request.responseText);}};for (let i = 0; i < files.length; i++) {formData.append(files[i].name, files[i])}request.send(formData);
};

Finally, call the method with an array of files as argument:

最后,以文件数组作为参数调用该方法:

fileInput.addEventListener("change", event => {const files = event.target.files;uploadFile(files);
});

Next, you can check out these advanced tutorials for how to use FormData with Angular, Ionic and React:

接下来,您可以查看这些高级教程,了解如何将FormData与Angular,Ionic和React结合使用:

  • How to Post FormData with Angular 7

    如何使用Angular 7发布FormData

  • React & Axios FormData

    React和Axios FormData

  • Multiple File Upload with Ionic 4 & FormData

    使用Ionic 4和FormData进行多文件上传

翻译自: https://www.freecodecamp.org/news/formdata-explained/

formdata多文件上传

formdata多文件上传_如何使用FormData轻松上传单个或多个文件相关推荐

  1. java 移动页面中的图片上传_移动端图片操作——上传

    上传我们一般都是用"input[type=file]"控件.当你用此控件时,你就授权了网页和服务器访问对应的文件,就可以得到File对象. 友情提示在,在Android手机webv ...

  2. java 微信图片上传_微信小程序图片上传java端以及前端实现

    小程序的图片上传与传统的图片上传方式有一些不一样 如果你有幸看到这篇文章,恭喜你,你可以完美解决了. 话不多说,前后端代码一并奉上: (基于springmvc ) @Controller @Reque ...

  3. 安全扫描失败无法上传_重要通知丨开始上传!学院奖2020春季征集活动作品上传通道已经开启了!...

    Hi~各位同学们, 在经历了长达3个月居家创作期后, 你们的命题选好了没? 创作团队组好了没? 创意点策划出了没? 作品完稿了没? 不管怎样, 都要打起精神来了! 本次学院奖春季征集活动, 作品上传通 ...

  4. phpcms 会员头像h5上传_使用elementui的头像上传组件报错

    不知道是我前端的问题?还是后端的问题?请问这个组件默认就是post传值.对吧?是否需不需要再去设置请求协议什么的呢? `Access to XMLHttpRequest at 'http://11.1 ...

  5. vueform表单文件上传_峰哥说技术系列-8.Spring Boot文件上传(Form表单和Ajax方式)

    今日份主题 Spring Boot文件上传(Form表单和Ajax方式) 在Spring Boot中,和文件上传的主要和MultipartResolver接口有关,他有两个实现类 StandardSe ...

  6. jsp文件上传_文件上传

    一.文件上传的目的--脚本文件 文件上传的一共可造成三种危害,从低到高分别是,任意内容文件,html文件,脚本文件. 任意内容文件 任意内容文件指的是虽然文件后缀不可控,但是文件内容可控,比如我可以上 ...

  7. vue 文件及描述信息一起上传_用Vue实现一个大文件上传和断点续传

    前言 这段时间面试官都挺忙的,频频出现在博客文章标题,虽然我不是特别想蹭热度,但是实在想不到好的标题了-.-,蹭蹭就蹭蹭 :) 事实上我在面试的时候确实被问到了这个问题,而且是一道在线 coding ...

  8. apache_fileupload实现文件上传_上传多个文件

    1.导包 核心类: DiskFileItemFactory – 设置磁盘空间,保存临时文件.只是一个具类. ServletFileUpload  - 文件上传的核心类,此类接收request,并解析r ...

  9. java web 断点上传_使用WebUploader实现分片断点上传文件功能(二)

    写在前面: 这几天,有去研究一下WebUploader上传文件,前面的博客有记录下使用WebUploader简单上传文件的例子,今天就把分片断点上传的例子也记录下吧,在博客园中,也查看了一些资料,基本 ...

最新文章

  1. Ubuntu 14.04 hadoop单机安装
  2. 计算机网络第四章-网络层复习笔记
  3. 安卓编程用什么软件_震惊!安卓IOS都可以用的牛逼软件
  4. 网络基础知识_你家的网络是这么布线的吗?家庭网络布线基础知识普及!
  5. buildroot自带程序(库)编译并安装
  6. 华为8月9日鸿蒙红包,华为正是宣布,“鸿蒙”系统8月9日上线,来看看有没有你的手机...
  7. corn表达式的简单使用
  8. 数据分析学习笔记——Pandas库思维导图
  9. input输入框清除样式
  10. FR跨SHEET条件汇总
  11. 学习笔记(12):Google开发专家带你学 AI:入门到实战(Keras/Tensorflow)(附源码)-深度学习“四件套”:数据、模型、损失函数与优化器
  12. Win10系统中查看是否开启虚拟化
  13. 跨境电商与国内电商运营得区别
  14. PE文件格式系列译文之
  15. java获取首字母_Java 获取中文首字母的方法
  16. PB9核心之——数据窗口对象使用
  17. 通信协议——Uart、RS232、RS485、SPI
  18. 更换matlab版本需要注意事项,AMD 篇四:更换Matlab调用MKL库版本
  19. linux系统有哪些手机,li手机操作系统排行_linux操作系统排行
  20. 华为鸿蒙os尝鲜,华为鸿蒙os尝鲜版

热门文章

  1. Java—System类和Runtime类
  2. Kubernetes-卷/存储卷(emptyDir/hostPath/pv/pvc)(十)
  3. django-模板语言dtl-render
  4. dj鲜生-31-用户中心-功能需求分析
  5. dj鲜生-26-登陆时-记住用户名的操作
  6. linux-mysql了解
  7. linux-权限操作,数字法
  8. kubernetes安装Helm
  9. Slog59_项目上线之域名备案时两家或多家运营商之间的业务交叉经历
  10. 使用 store 来优化 React 组件