Store Input File Selected in Redux to Upload Later

2019-08-31 14:20发布

问题:

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.

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?

回答1:

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.

When you finally process the form inputs you can use this value to load and send the file to the server. As per MDN

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.

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:

  1. Set the method attribute to POST because file content can't be put inside URL parameters.
  2. Set the value of enctype to multipart/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).

  3. Include one or more File picker widgets to allow your users to select the file(s) that will be uploaded.