Technology Encyclopedia Home >How to implement file upload and download in NativeScript?

How to implement file upload and download in NativeScript?

Implementing file upload and download in NativeScript involves using the file system module to interact with the device's storage. For uploading files, you typically use HTTP requests to send the file data to a server. For downloading, you fetch the file from a server and save it locally.

File Upload Example:

const fs = require('@nativescript/core/file-system');
const http = require('@nativescript/core/http');

function uploadFile(filePath) {
    const request = {
        url: 'https://example.com/upload',
        method: 'POST',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        description: 'Uploading file...',
        timeout: 20000
    };

    const file = fs.File.fromPath(filePath);
    const formData = new FormData();
    formData.append('file', file);

    request.content = formData;

    http.request(request).then((response) => {
        console.log('File uploaded successfully');
    }).catch((err) => {
        console.error('Error uploading file', err);
    });
}

File Download Example:

const fs = require('@nativescript/core/file-system');
const http = require('@nativescript/core/http');

function downloadFile(url, savePath) {
    const request = {
        url: url,
        method: 'GET',
        headers: {
            'Content-Type': 'application/octet-stream'
        },
        description: 'Downloading file...',
        timeout: 20000
    };

    http.request(request).then((response) => {
        const file = fs.File.fromPath(savePath);
        file.writeTextSync(response.content.toString());
        console.log('File downloaded successfully');
    }).catch((err) => {
        console.error('Error downloading file', err);
    });
}

For cloud-based storage and management of files, consider using services like Tencent Cloud's COS (Cloud Object Storage), which provides a robust solution for storing and retrieving files in the cloud, integrating well with NativeScript applications for scalable file handling.