typescript - 如何在 ionic2 上传前获取文件名和 mime 类型?

标签 typescript cordova ionic-framework file-upload ionic-native

我正在尝试使用 ionic/file-chooser 插件的帮助上传文件。一切都很完美,直到我没有收到上传文档或 pdf 文件的要求。 我正在使用 ionic 3.12.0 和 cordova 7.0.1。

 const fileTransfer: FileTransferObject = this.transfer.create();
    let options: FileUploadOptions = {
      fileKey: 'files0',
      fileName: 'name.jpg',
      params: {
        Authkey: this.CS.auth_key,
        Token: this.CS.token,
        group_id: this.CS.activeGroupId,
        Userid: this.CS.userId
      }
    };
    this.fileChooser.open()
      .then(uri => {
        this.CS.show_loader();
        //alert(uri );
        this.file.resolveLocalFilesystemUrl(uri)
          .then((files)=> {
          alert(JSON.stringify(files, null, 4));
        }).catch((err) => {
          alert(JSON.stringify(err, null, 4));
        });
        //let name = uri.split("/");
        //options.fileName = name[name.length - 1];
       // alert(options.fileName);
        fileTransfer.upload(uri, this.CS.base_url + 'groups/uploadChat', options)
          .then((data) => {
            this.CS.hide_loader();
            this.res = data;
            //alert(JSON.stringify(data, null, 4));
            let d = JSON.parse(this.res.response);

            if(d.status == 1){
              let a = {
                member_id: this.user_id,
                imageLink: this.groupChatData.loginUserData.imageLink,
                message: '',
                attachment: d.data[0].attachment,
                member_name: this.CS.userData.name,
                mime_type: d.data[0].mime_type,
                attachment_imageUrl: d.data[0].attachment_imageUrl,
                attachment_linkUrl: d.data[0].attachment_linkUrl,
                send_at: Date.now()
              };
              this.group_chat.push(a);
              setTimeout(() => this.content.scrollToBottom(), 200);
            }else{
              this.CS.alertMessage("error", this.res.response.message);
            }

          }, (err) => {
            alert(JSON.stringify(err, null, 4));
          })
      })
      .catch(e => alert(JSON.stringify(e, null, 4)));

resolveLocalFilesystemUrl 返回这样的东西 -

enter image description here

既没有文件名也没有文件类型,那么如何将文件名发送到服务器?

最佳答案

第一个解决方案

要获取文件名和文件 mime,请尝试以下操作:

首先你需要安装以下插件:

  1. fileChooser
  2. filePath
  3. file

然后您可以执行以下操作:

  this.fileChooser.open().then(uri =>
    {
      console.log(uri);
      this.filePath.resolveNativePath(uri).then(filePath =>
        {
          this.filesPath = filePath;
          this.file.resolveLocalFilesystemUrl(filePath).then(fileInfo =>
            {
              let files = fileInfo as FileEntry;
              files.file(success =>
                {
                  this.fileType   = success.type;
                  this.filesName  = success.name;
                });
            },err =>
            {
              console.log(err);
              throw err;
            });
        },err =>
        {
          console.log(err);
          throw err;
        });
    },err =>
    {
      console.log(err);
      throw err;
    });

这适用于 android,fileChooser.open() 插件将打开文件系统,因此您可以选择一个文件,filePath.resolveNativePath(uri) 将提供你是文件的路径。

resolveLocalFilesystemUrl(filePath) 方法将为您提供问题中显示的有关文件的信息。它还返回类型为 Entry 的 Promise,其中不包含名称和类型。

因此您需要使用 as 关键字将其转换为类型 FileEntry它将包含 nametype


第二种解决方案

  fileUpload()
 {
 this.arrayType = ["txt", "pdf", "doc", "docx", "xls", "xlsx", "rtf", "gif", "csv"];
if(this.platform.is("ios"))
{
  this.filePicker.pickFile().then(uri=>
  {
    console.log(uri);
    this.filesPath  = uri;
    this.fileName   = filesPath.substring(filesPath.lastIndexOf("/") + 1);
    this.fileType   = this.fileName.substring(this.fileName.lastIndexOf(".") + 1);
  },err=>
  {
    console.log(err);
    throw err;
  });
}
else if(this.platform.is("android"))
{
  this.fileChooser.open().then(uri =>
  {
    console.log(uri);
    this.paths = uri;
    this.filePath.resolveNativePath(uri).then(filePath =>
    {
      console.log(filePath);
      this.filesPath  = filePath;
      this.fileName   = filesPath.substring(filesPath.lastIndexOf("/") + 1);
      this.fileType   = this.fileName.substring(this.fileName.lastIndexOf(".") + 1);
      if(this.arrayType.indexOf(this.fileType) > -1)
      {
       console.log("accepted type");
      }
    },err=>
    {
      console.log(err);
      throw err;
    });
  },err=>
  {
    console.log(err);
    throw err;
  });
  }
}

此解决方案适用于 ios 和 android,这里首先检查用户使用的是哪个平台,然后使用 filepicker插件,您可以检索文件并使用 subString 您可以获得名称和类型。对于android,可以使用filePath插件的resolveNativePath(uri)方法获取文件的路径,然后使用subString可以得到名称和类型。

你也可以检查文件的类型是否在类型数组中。

关于typescript - 如何在 ionic2 上传前获取文件名和 mime 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967119/

相关文章:

javascript - 使用 100% 高度 div 填充 ion-content

angular - Ionic 4 Console.Log() 未显示在函数中

javascript - 转换字符串(url 样式)以在对象中导航

typescript - 扩展 typescript 变量声明

typescript - 如何强制回调参数的类型合规性

javascript - ionic http 获取本地文件给出 http 错误代码 0?

ios - Ionic 和 iOS 10 构建中的使用描述问题

javascript - 动态嵌套的 Angular Material 菜单

android - 在 Android Phonegap 应用程序中处理推送通知消息

android - 在 Angular 为4的组件中使用cordova插件