后台接口需要传输multipart/form-data 格式数据,经过PhotoViewPicker后拿到的图片路径,但是后台接口需要file对象。前端代码如下:
const formData = new FormData()
formData.append('file',e.file)
formData.append('fileName', e.fileName)
private openGalleryInternal() {
let photoPicker = new picker.PhotoViewPicker();
photoPicker.select({
MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
maxSelectNumber: 1
}, (error, result) => {
if (result) {
this.uploadImage(result.photoUris);
LogUtil.error(this.TAG, '')
result.photoUris.forEach((url) => {
console.log("url: " + url);
})
}
});
}
private uploadImage(paths: string[]) {
const allFiles = Array<request.File>()
for (let i = 0; i <paths.length; i++) {
let path = paths[i]
console.log("path: " + path)
allFiles[i] = {
name: "image" + i + ".jpg",
filename: "image" + i + ".jpg",
uri: path,
type: "jpg"
}
}
request.uploadFile(getContext(this), {
url: API_LIST.files,
method: "POST",
files: allFiles,
header: {
'content-type': 'multipart/from-data;boundary=----WebKitFormBoundaryn8D9asOnAnEU4Js0',
},
data: [
{
name: "fileName",
value: 'ceshi'
},
{
name: "file",
value: 这里应该传输一个file对象
},
{
name: "appId",
value: signHead.headData.appId
},
{
name: "uid",
value: signHead.headData.uid
},
{
name: "token",
value: signHead.headData.token
},
{
name: "deviceType",
value: signHead.headData.deviceType
}
]
}, (error, response) => {
if(response) {
response.on('progress', (uploadedSize: number, totalSize: number) => {
console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
})
} else {
console.log("upload failure: " + error)
}
});
}
通过PhotoViewPicker获取到的图片不能直接用于传输,可以通过将其复制在应用沙箱路径下,然后再用沙箱路径下的文件进行传输。 下面是部分demo: