目录

Upload and Download

Data processed by the quick app APIs may be read by other apps when being used on a PC. Therefore, you are not advised to store sensitive data.

API Declaration

Add the following configuration to the features attribute in the manifest.json file:

{"name": "system.request"}

Module Import

Add the following configuration to the script element on the page where the API will be called:

import request from '@system.request'

Or

var request = require("@system.request")

Application Scope

Item

Description

Applicable devices

Mobile phones and tablets

Applicable regions

Global

Definition

API

Description

request.upload(OBJECT)

Uploads a file.

request.download(OBJECT)

Downloads a file.

request.onDownloadComplete(OBJECT)

Listens to download tasks.

[h2]request.upload(OBJECT)

Description

Uploads a file.

In 1060 and later versions, you can use config.network in the manifest.json file to configure the network timeout.

OBJECT parameters

Parameter

Type

Mandatory/Optional

Description

url

string

Mandatory

Resource URL.

header

object

Optional

Request header, which accommodates all attributes of the request. The setting of useragent is invalid.

method

string

Optional

The options are POST and PUT. The default value is POST.

files

array

Mandatory

List of files to be uploaded, which is submitted through multipart/form-data. If you want to use the application/octet-stream mode, use the data request API to upload data. The value of files is an array of file objects. For the structure of the file object, please refer to files parameters.

data

array

Optional

Additional form data in an HTTP request.

success

function

Optional

Callback upon success.

fail

function

Optional

Callback upon failure.

complete

function

Optional

Callback upon completion, regardless of whether the API call is successful or fails.

files parameters

Parameter

Type

Mandatory/Optional

Description

filename

string

Optional

File name in the header when multipart is submitted. If the file name is not specified here, the file name is obtained from the URI by default.

name

string

Optional

Project name of the form when multipart is submitted. The default value is file.

uri

string

Mandatory

Local address of the files to be uploaded.

type

string

Optional

Content-Type of the files to be uploaded. If this parameter is left empty, the system queries the mapping table for Content-Type based on the filename or uri suffix. If Content-Type cannot be obtained, an error message is displayed, indicating that the parameter is invalid.

data parameters

Parameter

Type

Mandatory/Optional

Description

name

string

Mandatory

Name of the form element.

value

string

Mandatory

Value of the form element.

Parameters returned in success

Parameter

Type

Description

code

number

Server status code.

data

string

If the value of type in the header returned by the server is text/*, application/json, application/javascript, or application/xml, the value is text. Otherwise, the value is the URI of a temporary file. If the value is an image or a video, it can be displayed on the image or video control.

headers

object

All headers in the response from the server.

Sample code

request.upload({
    url: "https://www.example.com",
    header: { "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,en-US;q=0.8,en;q=0.6" },
    files: [
    {
        uri: "internal://xxx/xxx/test",
        name: "file1",
        type: "test.png"
    }
    ], data: [
    {
        name: "key1",
        value: "value1"
    }
    ],
    success: function (data) { 
        console.log("handling success"); 
    },
    fail: function (data, code) {
        console.log("handling fail, code=" + code);
    }
})

[h2]request.download(OBJECT)

Description

Downloads a file.

The downloaded file is stored on a user's mobile phone. They can go to /Android/data/com.huawei.fastapp.dev/files/fastappEngine/ using the file manager to manage the downloaded file. The downloaded file will be stored until the user clears the quick app data.

OBJECT parameters

Parameter

Type

Mandatory/Optional

Description

url

string

Mandatory

Resource URL.

header

object

Optional

Request header, which accommodates all attributes of the request. The setting of useragent is invalid.

description (1010+)

string

Optional

Download description, which is used as the title on the notification bar. The default value is the file name.

filename (1010+)

string

Optional

Download file name, which is obtained from the network request or URL by default.

The value can be:

  • File name: The file name can contain only letters, digits, and underscores (_).
  • File name extension: The file name extension must be standard, which can contain only letters and digits, for example, txt and mp4.

success

function

Optional

Callback upon success.

fail

function

Optional

Callback upon failure.

complete

function

Optional

Callback upon completion, regardless of whether the API call is successful or fails.

Parameters returned in success

Parameter

Type

Description

token

number (versions earlier than 1076)

string (1076+)

Download token, based on which the download status is obtained.

Sample code

request.download({
    url: "https://www.example.com",
    success: function (data) { 
        console.log("handling success" + data.token); 
    },
    fail: function (data, code) {
        console.log("handling fail, code=" + code);
    }
})

[h2]request.onDownloadComplete(OBJECT)

Listens to download tasks.

OBJECT parameters

Parameter

Type

Mandatory/Optional

Description

token

string

Mandatory

Token returned by the download API.

success

function

Optional

Callback upon success.

fail

function

Optional

Callback upon failure.

complete

function

Optional

Callback upon completion, regardless of whether the API call is successful or fails.

Parameters returned in success

Parameter

Type

Description

uri

string

URI of the files to be downloaded, which is stored in the mass partition of the file structure. You can use the file manager to go to the /Android/data/com.huawei.fastapp.dev/files/fastappEngine/ directory and find these files.

Result codes returned in fail

Result Code

Description

1000

Download fails.

1001

The download task does not exist.

Sample code

request.onDownloadComplete({
    token: "123",
    success: function (data) {
        console.log("handling success" + data.uri);
    },
    fail: function (data, code) {
        console.log("handling fail, code=" + code);
    }
})

Demo

<template>
    <div>
        <div>
            <text>{{componentName}}</text>
        </div>
        <div>
            <div>
                <text>Download file: {{fileDownloadData}}</text>
            </div>
            <input type="button" onclick="downloadFile" value="Download file"/>
            <div>
                <text>Download file path: {{fileDownloadUri}}</text>
            </div>
            <input type="button" onclick="downloadFileComplete" value="File download status"/>
            <div>
                <text>Upload file: {{fileUploadData}}</text>
            </div>
            <input type="button" onclick="uploadFile" value="Upload file"/>
        </div>
    </div>
</template>
<style>
    @import '../Common/css/common.css';
    .item-container {
        margin-bottom: 50px;
        margin-right: 60px;
        margin-left: 60px;
        flex-direction: column;
    }
    .item-content {
        flex-direction: column;
        background-color: #ffffff;
        padding-left: 30px;
        padding-right: 30px;
        padding-top: 20px;
        padding-bottom: 20px;
        margin-bottom: 30px;
        align-items: flex-start;
    }
    .txt {
        lines: 5;
        padding-top: 15px;
        padding-bottom: 15px;
    }
</style>
<script>
    import request from '@system.request'
    import prompt from '@system.prompt'
    export default {
        data: {
            componentName: 'request',
            fileDownloadData: '',
            fileUploadData: '',
            fileDownloadUri:""
        },
        onInit: function () {
            this.$page.setTitleBar({ text: 'request' })
        },
        downloadFile: function () {
            var that = this;
             // Download a file and save it to the local host.
          request.download({
                url: 'https://www.huawei.com/Assets/CBG/img/logo.png',
                description: 'This is description.',
                filename: 'HuaweiLogo.png',
                success: function (ret) {
                    that.fileDownloadData = ret.token;
                    console.log('file_download_data--------' + JSON.stringify(ret.token));
                    prompt.showToast({
                        message: 'file_download_data--------' + JSON.stringify(ret.token)
                    })
                },
              fail: function (errmsg, errcode) {
                  prompt.showToast({
                      message: "Download failure: "+errcode + ':' + errmsg
                  })
              }
            })
        },
        downloadFileComplete: function () {
            var that = this;
             // Download a file and save it to the local host.
            console.log('Download a file');
            request.onDownloadComplete({
                token:that.fileDownloadData,
                success: function (ret) {
                    that.fileDownloadUri = ret.uri;
                    console.log('fileDownloadUri--------' + JSON.stringify(ret.uri));
                    prompt.showToast({
                        message: 'fileDownloadUri--------' + JSON.stringify(ret.uri)
                    })
                },
                fail: function (errmsg, errcode) {
                    prompt.showToast({
                        message: "Download failure: "+errcode + ': ' + errmsg
                    })
                }
            })
        },
        uploadFile() {
            var that = this;
            // Upload a local file. In the preceding command, data indicates the request parameter, and files indicates the list of files to be uploaded.
            request.upload({
                url: "https://117.78.33.207:48080/uploadDemo/api/uploadFile",
                header:{"Accept-Encoding": "gzip, deflate","Accept-Language": "zh-CN,en-US;q=0.8,en;q=0.6"},
                files: [
                    {
                        uri: that.fileDownloadUri,
                        name: "component_test.png",
                        type:"multipart/form-data"
                    }
                ],
                success: function (ret) {
                    that.fileUploadData = ret.data;
                }
            })
        }
    }
</script>

Version Change History

Version

Date

Description

1010

2018-04-20

Added the description and filename parameters to the request.download API for you to set the download description and name of the file to be downloaded.

Links

[h2]FAQs

[h2]Cases

Failure to Display Images Downloaded Through the File Download API