uploadPics(){
let fileUris = this.copyFileToSandBox();
let files: Array<request.File> = []
for (let i = 0; i < fileUris.length; i++) {
let file = fs.openSync(fileUris[i],fs.OpenMode.READ_ONLY);
let stat = fs.lstatSync(fileUris[i]);
fs.closeSync(file.fd);
let filename = fileUris[i].substring(fileUris[i].lastIndexOf("/") + 1);
let name = filename.substring(0,filename.indexOf("."));
let fileType = filename.substring(filename.indexOf(".") + 1);
let path = fileUris[i].substring(fileUris[i].lastIndexOf("/cache"))
files.push({
filename: name,
name: "files",
uri: "internal:/" + path,
type: fileType
})
};
let header = new Map<Object, string>();
header.set("Content-type","multipart/form-data")
let data : Array<request.RequestData> = [{name:"serviceCode",value:"handheld_bus_file"},{name:"twoServiceCode",value:"feedback"}];
let uploadConfig: request.UploadConfig = {
url: UrlConst.ROOT_URL + UrlConst.FILE_UPLOAD_URL,
header: header,
method: 'POST',
files: files,
data: data
}
try {
request.uploadFile(getContext(this), uploadConfig)
.then((uploadTask: request.UploadTask) => {
uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
}
});
uploadTask.on("headerReceive",(header:object)=>{
console.log(JSON.stringify(header));
//header.body为服务器返回的信息
})
/*uploadTask.delete(()=>{})
uploadTask.off('complete', (taskStates: Array<request.TaskState>) => {
for (let i = 0; i < taskStates.length; i++) {
console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
}
});*/
})
.catch((err: BusinessError) => {
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
})
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}
}
使用上述代码上传文件时,在
uploadTask.on("headerReceive",(header:object)=>{
console.log(JSON.stringify(header));
//header.body为服务器返回的信息
})
中接到文件不能为空,跟进后台后发现,无文件上传到服务器,该接口在友商平台调用正常,缓存中的文件有数据,未能分析出代码问题
参考示例: