Taro,react封装上传文件跟上传图片
taro小程序上传文件跟上传图片
·
export function apiUploadImage(token: string, type: 0 | 1 | 2 | 3 | 4 | 5 | 6, count = 1, cropScale: keyof Taro.cropImage.CropScale | '' = ''): Promise<{
fileUrl: string
filePath: string,
}[]> {
return new Promise(async (resolve, reject) => {
Taro.chooseMedia({
mediaType: ['image'],
count: count,
sourceType: ['album', 'camera'],
camera: 'front',
}).then(async data => {
Taro.showLoading({
title: '上传中'
})
if (data.tempFiles.length === 1 && cropScale !== '') {
try {
const { tempFilePath } = await Taro.cropImage({
src: data.tempFiles[0].tempFilePath, // 图片路径
cropScale
})
data.tempFiles[0].tempFilePath = tempFilePath
} catch (e) {
Taro.hideLoading()
return
}
}
const promises = data.tempFiles.map(image => {
return new Promise((reso, reje) => {
Taro.uploadFile({
header: {
Authorization: token
},
url: configData.host + `/xxx/xxx/xxx/xxxx/${type}`,
name: 'files',
filePath: image.tempFilePath,
success({ statusCode }) {
if (statusCode === 413) {
Taro.showToast({
title: '图片大小过大,请重新选择照片',
icon: 'none'
})
}
},
fail() {
Taro.showToast({
title: '图片上传失败,请重试',
icon: 'none'
})
}
}).then(result => {
const dat = JSON.parse(result.data);
if (result.statusCode === 200) {
if (dat.code === 'STATUS_000') {
reso({ ...dat.data[0], tempFilePath: image.tempFilePath });
} else {
reje(dat.msg)
Taro.hideLoading()
}
} else {
reje(result.errMsg)
Taro.showToast({
title: '图片上传失败,请重试',
icon: 'none'
})
}
}).catch(err => {
reje(err)
Taro.showToast({
title: '图片上传失败,请重试',
icon: 'none'
})
})
})
})
return Promise.all(promises).then(da => {
resolve(da as any)
Taro.hideLoading()
})
}).catch(err => {
reject(err)
Taro.showToast({
icon: 'none',
title: err
})
})
})
}
封装上传文件
export function apiUseractiveRouteUploadFile(token: string, count, bizType = 1): Promise<{
name: string
path: string
}[]> {
return new Promise((resolve, reject) => {
Taro.chooseMessageFile({
count: count,
type: 'file',
success: function (res) {
const file = res.tempFiles
if (!file.length) return;
Taro.showLoading({
title: '上传中'
})
return new Promise((reso, reje) => {
Taro.uploadFile({
header: {
Authorization: token
},
url: `${configData.host}/xxx/xxx/xxx/xxxxx/${bizType}`,
name: 'files',
filePath: res.tempFiles[0].path,
success({ statusCode }) {
if (statusCode === 413) {
Taro.showToast({
title: '图片大小过大,请重新选择照片',
icon: 'none'
})
}
}
}).then(result => {
if (result.statusCode === 200) {
const dat = JSON.parse(result.data);
if (dat.code === 'STATUS_000') {
reso(dat.data[0]);
} else {
reje(dat.msg)
Taro.hideLoading()
}
} else {
reje(result.errMsg)
Taro.hideLoading()
}
resolve(file as any)
Taro.hideLoading()
}).catch(err => {
reje(err)
reject(err)
Taro.hideLoading()
})
}).finally(() => {
Taro.hideLoading()
})
}
})
})
}
如何使用
apiUploadImage(user.token, 1, 1).then((data) => {
if (data.length) {
activeRoute.readBookImg = data[0].filePath
activeRoute.readBookImgPathUrls = data[0].fileUrl
}
setActiveRoute({ ...activeRoute })
});
更多推荐
已为社区贡献3条内容
所有评论(0)