Fetch implementation File Upload

Source: Internet
Author: User

Summary

This implementation complements several previously missed points.

The file submitted by input of form form type=file is a fixed type of object

Include file multiple properties

How to stitch the form data manually

Splicing when trying to use file reader to obtain the binary manually created file object, failed ... There are many properties that are missing from the file object found in the foreground, such as name, LastModified, type, and so on. Attempts to interact with the back end of the Blob object (the base class of file), and possibly some backend framework that can parse the contents of the binary file, can be used to interact directly with the file content, and we now use WEBX's older framework.
The stitching form data is as follows

Multipart/form-data mainly consists of three parts:

HTTP Header. Need to add head "CONTENT-TYPE:MULTIPART/FORM-DATA; boundary=%s ", this boundary is the delimiter, see the second article.
Delimiter boundary. A delimiter is a string that does not conflict with the contents of the body and is used to split multiple parameters. It is usually n minus + random string, such as "----------Current Time".
The text needs to be added to the header:
Content-disposition:form-data; Name= '%s ',%s is the variable name that needs to be passed.
Content-type: Specifies the body MIME type, the default is plain text text/plain, unknown type can fill Application/octet-stream.
Data. Note that the data encoding, the document said "7BIT encoding", iso-8859-1 can be

Note: The File object explains Https://developer.mozilla.org/en-US/docs/Web/API/File

Submitted Request content Type

Do not set manually, I initially set Multi-part/data, but the browser automatically generated boundary parameters, missing can not be resolved.

Here are a few common content-type:

1.text/html
2.text/plain
3.text/css
4.text/javascript
5.application/x-www-form-urlencoded
6.multipart/form-data
7.application/json
8.application/xml

Concrete project structure and code implementation

Front desk

<input type="file" onChange={this.uploadSuccess} accept=".xlsx" id="uploadFile"/><input type="file" onChange={this.uploadSuccess} accept=".xlsx" id="uploadFile"/>uploadSuccess = (e) => {  const { changeUploadFile } = this.props;  const _this = this;  var reader = new FileReader();  reader.onload = function (readerEvent) {    // 存储上传的文件    changeUploadFile(readerEvent.target.result);  // !! 这里可以获取到文件的二进制内容    _this.props.searchBatchUploadEntity(document.getElementById('uploadFile').files[0]);  };  reader.readAsText(e.target.files[0]);}

Shared worker Side

function Wrapformdata (options) {Const FORMDATA = new FormData ();    for (var key of Object.keys (options)) {Let value = Options[key];  Formdata.append (key, value); } return formData;} function Fetchapi (url,init) {init = init | |  {}; Init.headers = Init.headers | |  {}; Init.credentials = ' include '; For pass Cookie if (init.body) {Init.method = Init.method | |  ' POST '; } init.headers[' x-proxy-timeout ' = Init.timeout | |  Defaluttimeout;  var Bodyjson = false;    if (Object.prototype.toString.call (init.body) = = = ' [Object Object] ') {Bodyjson = true;  Init.body = Json.stringify (init.body); } console.time (' [performance]_network ', URL) return fetch (Url,init). Then (res) = {console.timeend (' [Performance]    _network ', url) if (res.status = = = 304) {return 304;    } if (Bodyjson) {init.body = Json.parse (init.body);    } if (!res.ok) {throw new Error (' ${res.status} ${res.statustext} '); } console.time (' [performance]_parse ', url) let ResU = Res.json ();    Console.timeend (' [performance]_parse ', url) return resu;  }, (err) = = {Throw err; });} function Fetchsuccess (url,init) {console.time (' [performance]_ ' +url) return Fetchapi (Url,init). then (data) = {C    Onsole.timeend (' [performance]_ ' +url) if (data = = = 304) {return 304; } if (Data.returncode) {throw new Error (Data.returnmessage | |    Json.stringify (data));  } return data.returnvalue;  }, (err) = = {Throw err; });} Const INIT = {method: ' Post ', Body:wrapformdata ({graphname, file,}), Accept: ' Application/json, application/ XML, Text/plain, text/html, *. * ',}fetchsuccess (ROUTER. Search_batch_upload_entity, init). Then ((result) = {CB (null, result);}, (err) = = CB (err);});

Fetch implementation File upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.