//将文件拷贝入沙箱中
copyFileToSandBox() : string[]{
let files : string[] = [];
let cachDir = this.context.cacheDir;
this.imgArr.forEach((uri) => {
let file = fs.openSync(uri,fs.OpenMode.READ_ONLY);
let name = file.name;
let dest = fs.openSync(cachDir + "/" + name,fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.copyFileSync(file.fd,dest.fd);
fs.closeSync(file.fd);
let destUri = dest.path;
fs.closeSync(dest.fd);
files.push(destUri);
})
return files;
}
//将文件上传服务器
uploadPics(){
if (this.imgArr && this.imgArr.length > 0 ) {
let fileUris = this.copyFileToSandBox();
let files: Array<request.File> = []
for (let i = 0; i < fileUris.length; i++) {
let filename = fileUris[i].substring(fileUris[i].lastIndexOf("/") + 1);
let name = filename.substring(0,filename.indexOf("."));
let fileType = filename.substring(filename.indexOf(".") + 1);
console.log("filename=" + filename + ";name=" + name + "type:" + fileType);
files.push({
filename: filename,
name: name,
uri: "internal:/" + fileUris[i],
type: fileType
})
};
let header = new Map<Object, string>();
header.set("Content-type","application/x-www-form-urlencoded")
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])}`);
}
});
})
.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}`);
}
}
}
上述代码中this.imgArr为从相册中选择的图片的uri数组,执行该代码后报错
Invoke uploadFile failed, code is 401, message is the parameters check fails Parameter verification failed, GetInternalPath failed, filePath is not valid
1.header.set(“Content-type”,“multipart/form-data”)
2.uri格式 uri: “internal:/” + ‘/cache/’+filename,
详见https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5\#file