上传文件
wx.cloud.uploadFile
//回调风格的API上传文件,会返回一个uploadTask对象
const uploadTask = wx.cloud.uploadFile({
cloudPath: 'example.png',//上传至云端的路径
/*cloudPath: 'file/example.png',//表示将文件保存在test文件夹*/
filePath: '',
success: res => {
//上传文件成功后会返回文件的File ID
//根据具体的使用需要对File ID进行操作
console.log(res.filID)
},
fail: err => {
//handle error
}
//在uploadTask对象上可以设置上传进度的监听回调
uploadTask.onProcessUpdata(res => {
console.log('上传进度',res.progress)
console.log('已上传的数据长度',res.totalBytesExpectedToSent)
console.log('预期需要上传的数据总长度',res.totalBytesExpectedToSend)
})
uploadTask.abort()//取消上传任务
})
promise
wx.cloud.uploadFile({
cloudPath: 'example.png',//上传至云端的路径
filePath: '',
}).then(res => {
//get resource ID
console.log(res.fileID)
}).catch(error =>{
//handle error
})
下载文件
//回调风格的API下载文件,会返回downloadTesk对象
wx.cload.downloadFile({
fileID: 'cloud: //xxx.png'//文件的File ID
sucess:res => {
//下载文件成功后会返回临时文件路径
console.log(res.temFilePath)
},
fail: err => {
//hadle error
}
})
//在downloadTask设置下载进度的监听回调
downloadTask.onProgressUpdate(res =>{
console.log('下载进度',res.progress)
console.log('已经下载的数据长度', res.totalBytesWritten)
console.log('预期需要下载的数据总长度',res.totalBytesExpectedWrite)
})
downloadTask.abort()//取消下载
promise
wx.cloud.downloadFile({
fileID: 'cloud://xxx.png',
}).then(res => {
//get temp file path
console.log(res.tempFilePath)
}).catch(error =>{
//handle error
})
下载文件成功实际上是被下载到一个临时的地方,如果希望永久存储文件,用wx.saveFile
wx.cloud.downloadFile({
fileID: 'cloud': 'xxx.png',//文件的File ID
success: res => {
wx.saveFile({
tempFilePath: res.temFilePath,
success (res2) {
const savedFilePath = res2.saveFilePath
}
})
}
})
删除文件
fileList
:是一个Object[]
类,数字中每个对象都有三个字段:fileID
(文件的fileID)、status
(状态码:0表示删除成功,)、errMsg
(删除操作得到的信息,成功为OK,失败为失败原因)
回调风格
wx.could.deleteFile({
fileList: ['cloud:xxx.png'],//file ID数组
success: res => {
console.log(res.fileList)
},
fail: err=> {
//handle error
}
})
Promise风格
wx.cloud.deleteFile({
fileList: ['cloud:xxx.png'],//file ID数组
}).then(res =>{
console.log(res.fileList)
}).catch(error => {
//handle error
})
获取文件临时URL
回调风格
wx.cloud.getTempFileURL({
fileList: ['cloud:xxx.png'],//file ID数组,
success: res =>{
console.log(res.fileList)
//fileList 是一个有如下结构的对象数组
//[{
// fileID: 'cloud:xxx.png',//文件ID
// tempFileURL: '',//文件的临时网络链接
// maxAge: 120 * 60 * 1000//有效期 单位为秒 默认为一天(86400s)
//}]
},
fail: err => {
//handle error
}
})
Promise风格
wx.cloud.getTempFileURL({
fileList: [{//将参数fileFileURL改为Object[ ]类型(可以自定义URL的有效时间)
fileID: 'cloud:xxx.png',
maxAge: 60 * 60//修改有效时间为1h
}]
}).then(res => {
console.log(res.fileList)
}).catch(res => {
//handle error
})