存储在Redux中选择的输入文件以供以后上传 [英] Store Input File Selected in Redux to Upload Later
问题描述
我有一个类型文件为React组件的输入.这是多页表单的一部分.因此,对于表单中的文本字段,我将数据存储在Redux中,以便最后可以在最后上传所有数据.
I have an input with type file as a React component. This is part of a multi-page form. So for text fields in the form I store the data in Redux so that at the end I can upload all the data at the very end.
这将对文本字段正常工作.但是对于需要输入文件的输入,我看不到它是如何工作的.
This will work fine for the text fields. But for an input where it takes in a file I don't see how this can work.
如何存储在Redux中选择的文件,以便最后可以将其作为数据的一部分上载?
How can I store the file selected in Redux so that at the end I can upload it as part of the data at the end?
推荐答案
您可以使用与存储其他文本字段相同的方式来存储文件. 类型为input
的value
属性file
包含另存为字符串的文件的路径.此值可以作为字符串字段保存在Redux存储中.
You can store the file in the same way your store other text fields. The value
attribute of a input
of type file
contains the path of the file saved as string. This value can be saved in the Redux store as a string field.
当您最终处理form
输入时,可以使用此值加载文件并将其发送到服务器.根据 MDN
When you finally process the form
inputs you can use this value to load and send the file to the server. As per MDN
使用HTML表单发送文件是一种特殊情况.文件是二进制数据(或被认为是二进制数据),而所有其他数据是文本数据.由于HTTP是文本协议,因此处理二进制数据有特殊要求.
Sending files with HTML forms is a special case. Files are binary data — or considered as such — whereas all other data is text data. Because HTTP is a text protocol, there are special requirements for handling binary data.
enctype
属性.该属性可让您指定
Content-Type
HTTP标头包含在请求中时
表格已提交.此标头非常重要,因为它告诉
服务器正在发送什么样的数据.默认情况下,其值为
application/x-www-form-urlencoded
.用人类的话来说,这意味着:
是已编码为URL参数的表单数据."
The enctype
attribute This attribute lets you specify the value of the
Content-Type
HTTP header included in the request generated when the
form is submitted. This header is very important because it tells the
server what kind of data is being sent. By default, its value is
application/x-www-form-urlencoded
. In human terms, this means: "This
is form data that has been encoded into URL parameters."
如果要发送文件,则需要执行三个额外的步骤:
If you want to send files, you need to take three extra steps:
- 将
method
属性设置为POST
,因为文件内容不能放在URL参数中. -
将
enctype
的值设置为multipart/form-data
因为数据将分为多个部分,每个文件一个 对于包含在表单主体中的文本数据加一个(如果文本也是 输入表格).
- Set the
method
attribute toPOST
because file content can't be put inside URL parameters. Set the value of
enctype
tomultipart/form-data
because the data will be split into multiple parts, one for each file plus one for the text data included in the form body (if text is also entered into the form).
包括一个或多个File picker
小部件以
允许您的用户选择将要上传的文件.
Include one or more File picker
widgets to
allow your users to select the file(s) that will be uploaded.
这篇关于存储在Redux中选择的输入文件以供以后上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!