import picker from '@ohos.file.picker'; import request from '@ohos.request'; import fs from '@ohos.file.fs'; import { PreferencesUtil } from '@pura/harmony-utils' import { ToastUtil } from '@pura/harmony-utils' interface imageUrl { filePath:string, fileAbsPath:string, } interface response { code:number, message:string, data:imageUrl } interface UploadResponseData { headers:object, body:string } const imageUrls:imageUrl={ filePath:'', fileAbsPath:'' }this.selectImage(getContext(this),this.token) async selectImage(context:Context,token:string) { const photoPicker = new picker.PhotoViewPicker const result = await photoPicker.select({ MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE, maxSelectNumber: 1 //上传图片的数量 }) if (result.photoUris?.length) { const addFolderName = 'animal' //取一个自己文件夹的名字(可省略) const defaultDir = context.cacheDir + '/' + addFolderName let files: request.File[] = [] //申明参数列表 result.photoUris.forEach(url => { //url是media地址 //fs 是操作文件的对象 //使用fs读文件 //读取沙箱路径 const file = fs.openSync(url, fs.OpenMode.READ_ONLY) //得到文件对象 //拷贝到沙箱目录下 cache/ //起一个唯一的文件名 !!! if (!fs.listFileSync(context.cacheDir).includes(addFolderName)) { fs.mkdirSync(defaultDir) } let ext = 'jpg' // 图片扩展名 let fileName = Date.now().toString() // 图片名称 let tempFileName = fileName + '.' + ext const fileUil = defaultDir + '/' + tempFileName fs.copyFileSync(file.fd, fileUil) files.push({ name: 'file', filename: tempFileName, type: ext, uri: `internal://cache/${addFolderName}/${tempFileName}` }) }) const config: request.UploadConfig = { url: 'http://......', //上传后端地址 method: 'POST', header: { "Authorization": 'bearer' + ' ' + JSON.parse(token), 'Content-Type': 'multipart/form-data' }, files, data: [], //在传文件过程传递一些其他的数据 如:data: [{ name: "businessId", value:"1222222222" }] }try{ const task = await request.uploadFile(context,config,) task.on('headerReceive',(header: object) => { let res = header as UploadResponseData; let data:response = JSON.parse(res.body as string) as response; //解析上传成功后返回的路径地址(http地址),接口的格式 if(data.code == 200) { console.log('headerCallback1',JSON.stringify(data.data)) }else { ToastUtil.showToast(data.message) } }); task.on('fail', (upFailCallback)=>{ ToastUtil.showToast(upFailCallback.toString()) console.log('headerCallback4',JSON.stringify(upFailCallback)) }) task.on('complete', (upFailCallback)=>{ ToastUtil.showToast(upFailCallback.toString()) console.log('headerCallback3',JSON.stringify(upFailCallback)) }) }catch (err) { ToastUtil.showToast(err) } }
鸿蒙开发之应用文件上传获取http地址(避坑指南)
于 2024-08-27 14:55:55 首次发布