本机脚本:如何从文件路径创建JS文件对象?

时间:2019-05-08 21:32:32

标签: android nativescript

我正在使用nativescript-imagepicker插件从手机库中选择图像。该插件允许我获取的内容之一就是文件的路径。

我需要能够使用表单数据将所选文件上传到服务器。为此,我需要先创建一个文件对象。

我如何使用文件路径来创建文件对象?

1 个答案:

答案 0 :(得分:2)

对于从相册上传图像,我强烈建议使用Nativescsript background http。要将图像上传到服务器,您必须将其保存在应用程序中,以便可以上传它们。我按照此处显示的示例Upload example进行操作。

将图像保存在本地后,如果需要其他数据,则需要使用multipartUpload并构造一个看起来像这样的请求。

let BackgroundHTTP = require('nativescript-background-http')
let session = BackgroundHTTP.session('some unique session id')
let request: {
    url: 'your.url.to/upload/images',
    method: 'POST',
    headers: {
        'Content-Type': 'application/octet-stream'
    }
    description: 'Uploading local images to the server'
}

//photos should have at least the filename from when you saved it locally.
let params = []
photos.forEach(photo => {
    params.push({name: photo.name, filename: photo.filename, value: 'ANY STRING DATA YOU NEED'})
}

let task = session.multipartUpload(params, request)

task.on('progress', evt => {
    console.log('upload progress: ' + ((evt.currentBytes / evt.totalBytes) * 100).toFixed(1) + '%')
}

task.on('error', evt => {
    console.log('upload error')
    console.log(evt)
}

task.on('complete', evt => {
    //this does not mean the server had a positive response
    //but the images hit the server.
    // use evt.responseCode to determine the status of request
    console.log('upload complete, status: ' + evt.responseCode)
}

相关问题