【问题标题】:Angular 10 + Nativescript Multipart File UploadAngular 10 + Nativescript 多部分文件上传
【发布时间】:2021-02-25 10:26:45
【问题描述】:

我正在尝试使用 Nativescript 7 从手机文件系统上传文件。我尝试了 nativescript-background-httpnativescript-http-formdata以及从 @angular/common/http 导入的 HttpClient 但这些方法似乎都不起作用。我的服务器正在运行 RocketChat (this is the API),我可以使用 Insomnia REST Client 成功上传文件。这是我第一次尝试使用 Angular HttpClient:

const formData = new FormData();
var file = this._audioFolder.getFile("file.mp3");
formData.append("file", file, "file.mp3");
this.httpClient.post<any>("https://myserver.com/api/...", formData, {
  headers: {
    "X-Auth-Token": "my_token",
    "X-User-Id": "my_id",
    "Content-Type": "multipart/form-data; boundary=---011000010111000001101001"
  }
}).subscribe((resp) => {
  console.log(resp);
}

返回错误:“文件”类型的参数不可分配给“字符串”类型的参数 | Blob' 当我将 file 附加到 formData.然后我尝试使用以下代码将我的文件转换为 Blob:

getBase64String(file: fs.File) {
  const data = file.readSync();
  //data.base64EncodedStringWithOptions(0); iOS
  return android.util.Base64.encodeToString(data, android.util.Base64.NO_WRAP);
}

然后

const blob = new Blob([base64file], {type: "audio/mp3"});
formData.append("file", blob, "file.mp3");

FormData append 方法接受了,但是响应返回了错误:

"error": {
    "success": false,
    "error": "File required"
}

然后在GitHub上找到this的解决方案,对这部分很感兴趣:

formData.append('file', {
  uri: fileInfo.path,
  type: fileInfo.type,
  name: encodeURI(fileInfo.name) || 'fileMessage'
});

但返回错误:Argument of type '{ uri: string;类型:字符串;名称:字符串; }' 不可分配给类型为 'string | 的参数斑点'。

我的猜测是,从 nativescript/file-system 派生的类 File 非常奇特,不能被视为 Blob。我也尝试使用 atob 函数将其转换为缓冲区数组,但方法未定义。

之后,我已经安装了 nativescript-background-http 并按照this 的示例进行操作,但这里出现错误:

var task = session.uploadFile(file, request);

告诉我没有 new 就不能调用 Observable 的实例。该行的 nativescript-http-formdata 也是如此:

let fd = new TNSHttpFormData();

这很令人困惑,因为这是一个非常 basic 的操作,并且每个使用此插件的人都必须实例化该类。

现在,我还能尝试解决/解决这些问题吗?我无法修改后端 API,但我可以尝试任何您能想到的方法来使用 http post 上传简单文件。

【问题讨论】:

    标签: angular typescript file http nativescript


    【解决方案1】:

    最后我找到了解决方案:如here 所写,如果您使用的是 Nativescript 7,则必须运行

    tns plugin add @nativescript/background-http
    

    而不是

    tns plugin add nativescript-background-http
    

    令人惊讶的是,官方npmjs页面上并没有提及。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2016-11-29
      • 2018-10-15
      • 2014-10-31
      • 2017-11-05
      • 2015-04-10
      • 2017-02-20
      相关资源
      最近更新 更多