Implementing React Native's File Upload with Pure Javascript

React Native is the most worthwhile mobile development technology to follow in the past two years. This project started as a hackathon project within Facebook in 2013. Before July 2014, this project was biased towards experimental nature, until the advertising management team wanted to. To build a standalone iOS app, the team had no engineers with iOS development experience, so the ad team worked closely with the React Naitve team over the next few months to move the project forward. In February 2015, the iOS version of Ads Manager was released on the App Store, indicating that the product can be used in production environments. Then in March 2015, at Facebook's F8 conference, the project announced open source and released the source code of React Naitve. Meanwhile, Android versions of React Native and Ads Manager are also in development. In June 2015, the Android version of Ads Manager was released to the Play Store. On September 14, amid the long-awaited expectations, the Android version of React Native was released. At the F8 conference that just ended this year, Microsoft also embraced React Native and released it. Their progress and plans for porting React Naitve to Windows and releasing React Naitve-based F8 UMP.

This article will cover:

Unfortunately, this project is all implemented based on native code. Although there is good tool support for using Native Comment in React Native, it is not more convenient to use pure JS libraries directly. In fact, React Native has quietly supported file uploading. We can use a few lines of JS to solve file problems without introducing any dependencies.

let formData = new FormData();
formData.append('file', {uri: uri, type: 'application/octet-stream',
name: key});
formData.append('key', key);
formData.append('token', token);
let options = {};
options.body = formData;
options.method = 'post';
return fetch(conf.UP_HOST, options).then((response) => {
});

Is it very simple and straightforward? The above lines of code correspond to the html form similar to this, we use these lines of code to simulate a file upload form

<form method="post" action="http://upload.qiniu.com/"
enctype="multipart/form-data">
<input name="key" type="hidden" value="<resource_key>">
<input name="x:<custom_name>" type="hidden"
value="<custom_value>">
<input name="token" type="hidden" value="<upload_token>">
<input name="file" type="file" />
<input name="crc32" type="hidden" />
<input name="accept" type="hidden" />
</form>

The corresponding Http request is similar to the following

POST / HTTP/1.1
Host: upload.qiniu.com
Content-Type: multipart/form-data; boundary=<frontier>
Content-Length: <multipartContentLength>
--<frontier>
Content-Disposition: form-data; name="token"
<uploadToken>
--<frontier>
Content-Disposition: form-data; name="key"
<key>
--<frontier>
Content-Disposition: form-data; name="<xVariableName>"
<xVariableValue>
--<frontier>
Content-Disposition: form-data; name="crc32"
<crc32>
--<frontier>
Content-Disposition: form-data; name="accept"
<acceptContentType>
--<frontier>
Content-Disposition: form-data; name="file";
filename="<fileName>"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
<fileBinaryData>
--<frontier>--

The following is a detailed analysis of the role of these short lines of code.

let formData = new FormData();
formData.append('file', {uri: uri, type: 'application/octet-stream',
name: key});
formData.append('key', key);
formData.append('token', token);

We first create a FormData object. The FormData object refers to the content of a Form form object. Here we only need to pay attention to the content in the Form and their Content-Type. Here we add the key, token and file forms. content, and specifies that the type of Content-Disposition of the file is application/octet-stream, which means that this is an arbitrary binary data, which can be png, jpeg pictures and any other types. The key and token are additional information required by the server. The key is the filename uploaded to the server, and the token is the request token. Finally, in the process of submitting the request with fetch, FormData will help us add information such as the Content-Type of Http itself.

let options = {};
options.body = formData;
options.method = 'post';
return fetch(conf.UP_HOST, options).then((response) => {
});

These four short lines of code help us build the Http payload and actually submit it to the uploading server. The actual returned server-side response needs to be processed by the client. You can use the Promise API of fetch, which is very convenient

fetch(url).then((response) => {
return response.text();
}).then((responseText) => {
self.setState({info: responseText});
}).catch((error) => {
console.warn(error);
});

There is a pit here that needs to be reminded. When the debug returns the response, you will find that the request will not enter the second Promise after the end of one Promise, send the request again, and find that the previously requested Promise continues to execute. This is actually a bug of React Native Debugger, you can ignore it, and everything is normal in non-debug mode. With the above knowledge, we can easily upload files to the server. There are many small partners who will choose services like Qiniu cloud storage to speed up development. According to Qiniu's official documents, the token can be uploaded. Here are seven Niu also launched the SDK of the React Native platform very intimatelyhttps://github.com/qiniu/react-native-sdk

After using the SDK, uploading files becomes very simple. The first is to install

$ npm i react-native-qiniu --save

After installation, configure your own AK and SK, which can be found in the personal center

var qiniu = require('react-native-qiniu');
qiniu.conf.ACCESS_KEY = <AK>
qiniu.conf.SECRET_KEY = <SK>

Here we give another real-world example. The user selects a picture in the picture library and uploads it to Qiniu cloud storage, because currently React Native does not officially support obtaining pictures from multiple channels such as picture library and camera. The code here uses Another open source library [ https://github.com/marcshilling/react-native-image-picker](https://github.com/marcshilling/react-native-image-picker ) . Complete demo: [ https://github.com/buhe/present-demo/tree/master/presentdemo](https://github.com/buhe/present-demo/tree/master/presentdemo )

Qiniu, as a cloud computing company that keeps up with technology trends, has been following up on the technology since the release of React Native. This year, it released the official version of the storage SDK to help small partners who use React Native to start a business more convenient. The use of Qiniu cloud storage reduces R&D costs and focuses on business models and technological innovation. Qiniu Cloud will continue to release cloud services for enterprises, and will also release the SDK of the React Native platform as soon as possible, allowing small partners who use React Naitve to integrate the latest services of Qiniu Cloud as soon as possible.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325446181&siteId=291194637