import { request } from '@kit.BasicServicesKit';
旧版 | |
新版 |
第一种方法 按照他的格式来写,实际上我们用的新的API,但是用的是旧版本的
Property 'on' does not exist on type 'void & Promise<UploadTask>'. <ArkTSCheck>
Property ‘on‘ does not exist on type ‘void & Promise<UploadTask>‘. <ArkTSCheck>-CSDN博客
第二种方法 我想试一下AS 断言看看能不能行
Conversion of type 'void & Promise<UploadTask>' to type 'UploadTask' may be a mistake because neither type sufficiently overlaps with the other. Type 'void & Promise<UploadTask>' is missing the following properties from type 'UploadTask': on, off, remove, delete <ArkTSCheck>
直接报错,这个方法不行 只能用 .then()方法写了
第三种方法 格式问题 (关键点)
我发现全部加上双引号他就从没有报错了 格式也变成了新版本的API格式,但是这样还有一个问题,就是固定了名字。不能改,所以得改进方法
interface File {
filename: string;
name: string;
uri: string;
type: string;
}
看他定义的都是string类型的
//缓存图片
const imgName = img.photoUris[0].split('/').pop()
const context = getContext(this)
const imgUrl = `${context.cacheDir}/${imgName}`
//fileIo.copyFileSync(imgUrl, img.photoUris[0])
const file = fileIo.openSync(img.photoUris[0], fileIo.OpenMode.READ_ONLY)
fileIo.copyFileSync(file.fd, imgUrl)
//this.avatar = imgUrl
//上传图片
const task = await request.uploadFile(context, {
url: 'https://hmajax.itheima.net/api/uploadimg',
header: {
'content-type': 'multipart/form-data'
},
method: http.RequestMethod.POST,
data: [],
files: [{
filename: imgName,
name: 'img',
uri: `internal://cache/${imgName}`,
type: 'imgName'
}]
})
task.on('headerReceive', (res: object) => {
const IRes = res as IUploadRes
const imgUrl = JSON.parse(IRes.body) as IBody
//AlertDialog.show({ message: imgUrl.url })
this.avatar = imgUrl.data.url
})
他要加上双引号才能是string类型,问题肯定出在了 imgName 上
const imgName: string | undefined
这个imgName返回的类型有两个,所以他无法判断是不是string类型,所以就没有 .on()方法
这样就解决一半了,还有type没有解决
最终代码
//缓存图片
const imgName = img.photoUris[0].split('/').pop()!
const context = getContext(this)
const imgUrl = `${context.cacheDir}/${imgName}`
//fileIo.copyFileSync(imgUrl, img.photoUris[0])
const file = fileIo.openSync(img.photoUris[0], fileIo.OpenMode.READ_ONLY)
fileIo.copyFileSync(file.fd, imgUrl)
//this.avatar = imgUrl
//上传图片
const imgType = imgName.split('.').pop()!
const task = await request.uploadFile(context, {
url: 'https://hmajax.itheima.net/api/uploadimg',
header: {
'content-type': 'multipart/form-data'
},
method: http.RequestMethod.POST,
data: [],
files: [{
filename: imgName,
name: 'img',
uri: `internal://cache/${imgName}`,
type: imgType
}]
})
task.on('headerReceive', (res: object) => {
const IRes = res as IUploadRes
const imgUrl = JSON.parse(IRes.body) as IBody
//AlertDialog.show({ message: imgUrl.url })
this.avatar = imgUrl.data.url
})