【发布时间】:2019-05-09 06:03:13
【问题描述】:
我正在使用 nativescript-imagepicker 插件从手机图库中选择图像。这个插件允许我得到的东西之一是文件的路径。
我需要能够使用表单数据将此选定的文件上传到服务器。为此,我需要先创建一个文件对象。
如何使用文件路径来创建文件对象?
【问题讨论】:
标签: android nativescript
我正在使用 nativescript-imagepicker 插件从手机图库中选择图像。这个插件允许我得到的东西之一是文件的路径。
我需要能够使用表单数据将此选定的文件上传到服务器。为此,我需要先创建一个文件对象。
如何使用文件路径来创建文件对象?
【问题讨论】:
标签: android nativescript
对于从照片库上传图片,我强烈建议使用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)
}
【讨论】: