HarmonyOS 获取相册图片路径后,无法上传到自己服务器

1、获取系统相册地址:

/data/storage/el2/base/haps/entry/cache/IMG_20240716_160349.jpg

2、无法上传到自己服务器:

static async uploadFileAgent<T>(context: common.UIAbilityContext, url: string, fileName: string):Promise<string> {
  // 上传任务配置项
  let fileNameIndex = fileName.lastIndexOf("/")
  let dstFileName = fileName.substring(fileNameIndex+1, fileName.length)

  let attachments: Array<request.agent.FormItem> = [{
  name: dstFileName.split(".")[0],
  value: [
    {
      filename: dstFileName,
      path: fileName,
    },]
  },
  {name: 'head', value: JSON.stringify(_formatPar("").head)}
  ];

  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: HttpManage.baseUrl+url,
    mode: request.agent.Mode.FOREGROUND,
    overwrite: true,
    method: "POST",
    data: attachments,
    saveas: "./",
    headers: {'Accept': '*/*', 'Content-Type': 'multipart/form-data', 'token': PreferenceUser.userInfo.tokenId }
  };

// 将本地应用文件上传至网络服务器

return new Promise((resolve, reject) => {
  try{
    request.agent.create(context, config)
      .then((task: request.agent.Task) => {

        task.start((err: BusinessError) => {
          if (err) {
            let progress = `Failed to start the upload task, Code: ${err.code} message: ${err.message}`;
            console.log(progress)
            reject(progress)
          }
        });
        task.on('progress', async(progress) => {
          console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`);
        })
        task.on('completed', async(list) => {
          console.warn(`/Request upload completed`);
          resolve(JSON.stringify(list))
        })

      }).catch((err: BusinessError) => {
      let progress = `Failed to create a upload task, Code: ${err.code}, message: ${err.message}`;
      console.log(progress)
      reject(progress)
    })
  }catch(err){
    reject(JSON.stringify(err))
  }
})
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

可以使用axios参考示例:

import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import axios, { AxiosError, AxiosProgressEvent, AxiosResponse } from '@ohos/axios'
import { FormData } from '@ohos/axios'
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  @State message: string = 'hello World';
  context = getContext(this) as common.UIAbilityContext

  build() {
    Button('选择').onClick(() => {
      let uris: Array<string> = [];
      let documentViewPicker = new picker.PhotoViewPicker();
      documentViewPicker.select({
        MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 1
      }).then((photoSelectResult: picker.PhotoSelectResult) => {
        uris = photoSelectResult.photoUris;
        console.info('photoViewPicker.select to file succeed and uris are:' + uris);
        let fileSource = fs.openSync(uris[0], fs.OpenMode.READ_ONLY);
        let fileDes =
          fs.openSync(`${this.context.cacheDir}/1.jpg`, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
        fs.copyFileSync(fileSource.fd, fileDes.fd)
        fs.closeSync(fileSource);
        fs.closeSync(fileDes);

        let formData = new FormData()
        formData.append('file', `${this.context.cacheDir}/1.jpg`); //uri支持传入沙箱路径
        // 发送请求

      })
    })
  }
}

对应axios:

import axios from '@ohos/axios'
import { FormData } from '@ohos/axios'

let formData = new FormData()
formData.append('file', 'internal://cache/blue.jpg')
// formData.append('file', cacheDir + '/hello.txt'); uri支持传入沙箱路径

// 发送请求
axios.post<string, AxiosResponse<string>, FormData>('https://www.huawei.com/upload', formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  context: getContext(this),
  onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
    console.info(progressEvent && progressEvent.loaded && progressEvent.total ?
      Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
  },
}).then((res: AxiosResponse<string>) => {
  console.info("result" + JSON.stringify(res.data));
}).catch((err: AxiosError) => {
  console.error("error:" + JSON.stringify(err));
})

需要注意一下返回值类型。

分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 文件上传服务器问题
393浏览 • 1回复 待解决
请求服务器图片资源刷新卡片
930浏览 • 1回复 待解决
HarmonyOS Rcp.post上传图库文件至服务器
328浏览 • 1回复 待解决
从本机获取图片进行上传到spring后端
2413浏览 • 1回复 待解决
HarmonyOS如何上传图片到模拟相册
974浏览 • 1回复 待解决