記錄初接觸鴻蒙,遇到的一個問題,
需求是點擊一個圖片上傳的+號圖,訪問本地圖片,可以選擇多張圖片并上傳。
下面是圖片上傳后的方法:
//選擇圖片并上傳private async showPhotoPicker() {const maxImageCount = 3;const remainCount = maxImageCount - this.list.length;if (remainCount <= 0) {console.warn('最多只能上傳 3 張圖片');return;}const photoSelectOptions = new picker.PhotoSelectOptions();photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;photoSelectOptions.maxSelectNumber = remainCount;const photoPicker = new picker.PhotoViewPicker();const result = await photoPicker.select(photoSelectOptions);if (result && result.photoUris) {const context = getContext(this);const newList: string[] = [];const newFilesList: request.File[] = [];for (const uri of result.photoUris) {if (this.list.length + newList.length >= maxImageCount) {break;}try {const fileType = 'jpg'; // 可拓展為通過 URI 判斷const fileName = `${Date.now()}_${Math.floor(Math.random() * 10000)}.${fileType}`;const copyFilePath = `${context.cacheDir}/${fileName}`;const file = fs.openSync(uri, fs.OpenMode.READ_ONLY);fs.copyFileSync(file.fd, copyFilePath);fs.closeSync(file.fd);newList.push(uri); // 保存原圖路徑用于本地預覽newFilesList.push({filename: fileName,type: fileType,name: 'img',uri: `internal://cache/${fileName}`});} catch (error) {console.error('圖片拷貝失敗:', error);}}// 合并已有和新選的,最多保留3個this.list = [...this.list, ...newList].slice(0, maxImageCount);this.filesList = [...this.filesList, ...newFilesList].slice(0, maxImageCount);}}private async handleSubmit() {if (this.filesList.length > 0) {try {console.log('filesList', json.stringify(this.filesList))const context = getContext(this);this.imageList = [];const filesArray = Array.from(this.filesList);const uploader = await request.uploadFile(context, {url: '你的上傳文件接口',method: 'post',header: {'Content-Type': 'multipart/form-data'},files: filesArray,data: []});uploader.on('progress', (uploaded: number, total: number) => {console.log(`上傳進度: ${uploaded}/${total}`);});uploader.on('fail', (err: object) => {console.error('上傳失敗:', JSON.stringify(err));});uploader.on('headerReceive', (res: object) => {try {const resBody = JSON.parse(res['body'] ?? '{}') as uploadDataClass;console.log('上傳成功,返回內容:', resBody);if (resBody && resBody.status === '1' && Array.isArray(resBody.data)) {const newImageList = resBody.data.map((item) => {return {url: item.url} as UploadFileDtoClass;});this.imageList = [...this.imageList, ...newImageList];} else {console.warn('上傳接口返回格式不符合預期:', resBody);}} catch (err) {console.error('解析上傳結果失敗:', err);}});uploader.on('complete', (taskStates: Array<request.TaskState>) => {submitFeedback({'imgurls': this.imageList.map(item => item.url).join(','),其他數據}).then(res => {})})} catch (err) {console.error('上傳過程失敗:', err);}}}
這是調用:
Image($r('app.media.xxx')).width('30%').height('auto').backgroundColor('#EEEEEE').borderRadius(4).onClick(() => {this.showPhotoPicker()})