需要權限:ohos.permission.INTERNET
1.nodejs自定義書寫上傳后端接口
傳輸過來的數據放在files?.image下
router.post('/upload',(req, res) => {var form = new multiparty.Form();form.uploadDir='public/images/uploads'; //上傳圖片保存的地址(目錄必須存在)form.parse(req, function(err, fields, files) {// 1、fields:獲取表單的數據 2、files:圖片上傳成功返回的信息console.log(files,fields)const fileurl = Date.now()+ files?.image[0]?.originalFilename;let newPath = form.uploadDir + '/' +fileurlfs.renameSync(files.image[0].path,newPath);let imgUrl = myUrl.myUrl+'/images/uploads/' +fileurlres.send({code: '200',message: '數據上傳成功',data:imgUrl})})
})
2,在jq中請求(new FormData())
var fileImg;//讀取圖片function fileUpload(_this) {var fileReader = new FileReader();//創建文件讀取對象fileImg = _this.files[0];//獲取file組件中的文件}//上傳圖片function uploadPictures() {var formData = new FormData();//圖片if (fileImg != null) {formData.append("image", fileImg);}$.ajax({url: 'http://localhost:3333/api/img/upload',type: 'post',data: formData,processData: false,contentType: false,success: function (res) {// var res = JSON.parse(res);console.log('upload success', res);// $('.img').attr('src', res.path);debugger},error: function (err) {console.log('upload error', err);console.log(err);}});}
3.對比在鴻蒙arkts請求如下 -試用相冊的場景
參考官網
1.假設數據來源于相冊,以下是獲取相冊的數據,photoSelectResult.photoUris[0]是一個目錄的路徑, 但是不是context.cacheDir的路徑,
試用下載必須要在cacheDir目錄下面
async selectPhoto() {try {let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();PhotoSelectOptions.maxSelectNumber = 1;PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;let textInfo: photoAccessHelper.TextContextInfo = {text: '人像'};let recommendationOptions: photoAccessHelper.RecommendationOptions = {textContextInfo: textInfo};PhotoSelectOptions.recommendationOptions =recommendationOptions; // 將推薦參數賦值給 photoSelectOptions.recommendationOptionslet photoPicker = new photoAccessHelper.PhotoViewPicker();let photoSelectResult = await photoPicker.select(PhotoSelectOptions)if (photoSelectResult.photoUris.length == 1) {this.uploadFile(photoSelectResult.photoUris[0])}} catch (error) {let err: BusinessError = error as BusinessError;}}
2.因為必須是cacheDir目錄,從相冊拿到的的圖片就復制一份存在cacheDir
// 提取文件擴展名的函數getFileExtension(fileName: string): string {const lastDotIndex = fileName.lastIndexOf('.');if (lastDotIndex !== -1 && lastDotIndex < fileName.length - 1) {return fileName.slice(lastDotIndex + 1);}return '';}
。。。。。console.log('photoUris', photoUris)const extensionName = this.getFileExtension(photoUris) // 后綴名console.log('文件擴展名是:', extensionName);const cacheDir = context.cacheDir; // 緩存根目錄const names = 'phone' + Date.now() + '.' + extensionName // 文件名const cacheF = cacheDir + '/' + names // 緩存目錄路徑let file: fileIo.File | undefined;file = fileIo.openSync(photoUris, fileIo.OpenMode.READ_ONLY); // 打開現有的文件fileIo.copyFileSync(file.fd, cacheF); //復制一下到緩存文件fileIo.closeSync(file); // 關閉console.log('文件擴展名是:', extensionName, '----', names);
3。知道了cacheDir目錄就組裝參數
let files: Array<request.File> = [//uri前綴internal://cache 對應cacheDir目錄{filename: names,name: 'image', // 必須是image,因為接口拿的數據就是這個的第0項uri: 'internal://cache/' + names,type: extensionName}]let data: Array = [{ name: 'name', value: 'value' }];let uploadConfig: request.UploadConfig = {url: 'http://xxxxxxxxxxxxxxxx/api/img/upload',header: {// 根據項目添加
},method: 'POST',files: files,data: data,}// 將本地應用文件上傳至網絡服務器
try {request.uploadFile(context, uploadConfig).then((uploadTask: request.UploadTask) => {let headerCallback = (value: object) => {let str = JSON.stringify(value)console.log("http:success:", JSON.stringify(rstr ))};uploadTask.on('headerReceive', headerCallback);}).catch((err: BusinessError) => {console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);})
} catch (error) {let err: BusinessError = error as BusinessError;console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}
緩存目錄在cacheDir ="/data/app/el2/100/base/{找到自己的包名}/haps/entry/cache”
原理總結
使用相冊拿到的路徑,復制一份放在緩存路徑下, request.uploadFile(只能讀緩存的路徑。
通過 uploadTask.on(‘headerReceive’, headerCallback);拿到后端給我們的響應數據code
官網也還提供了request.agent,可查看文檔使用
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file-upload-download#%E4%B8%8A%E4%BC%A0%E5%BA%94%E7%94%A8%E6%96%87%E4%BB%B6