Angular 10 + Nativescript 分段文件上传

Angular 10 + Nativescript Multipart File Upload

我正在尝试使用 Nativescript 7 从 phone 文件系统上传文件。我已经尝试了 nativescript-background-httpnativescript-http-formdata 以及从 @angular/common/http 导入的 HttpClient 但 none这种方法似乎有效。我的服务器是 运行 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);
}

返回错误:'File' 类型的参数不可分配给 'string | Blob' 类型的参数,当我附加 file 形成数据。然后我尝试使用以下代码将我的文件转换为 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 附加方法接受了,但响应返回了错误:

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

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

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

但返回错误:类型为'{ uri: string; 的参数类型:字符串;名称:字符串; }' 不可分配给 'string | Blob'.

类型的参数

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

在那之后,我安装了 nativescript-background-http 并遵循 this 示例,但我在这里遇到错误:

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

告诉我如果没有 new 就不能调用 Observable 的实例。 nativescript-http-formdata 在该行发生了同样的情况:

let fd = new TNSHttpFormData();

这非常令人困惑,因为它是一个非常 basic 的操作,使用此插件的每个人 都必须实例化 class.

现在,我还能尝试 fix/workaround 那些问题吗?我无法修改后端 API,但我可以尝试 any 您可以想到的使用 http post.

上传简单文件的方法

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

tns plugin add @nativescript/background-http

而不是

tns plugin add nativescript-background-http

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