如果我只有PDF URL,我该如何发送PDF作为附件

时间:2018-06-07 06:26:01

标签: javascript ionic-framework email-attachments

我有一个离子应用程序,它根据用户的输入进行某些计算。计算完成后,结果将通过API(generatePDF)调用转换为PDF。另一个要求是通过电子邮件发送相同的PDF。 API(sendMail)也是为此而制作的。 enctype =' multipart / form-data' 在sendMail API的标头部分设置。

我现在有了PDF URL,我将其作为generatePDF API的响应。使用此URL如何将PDF附加到我打算发送的邮件中?

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

谢谢你@MissakBoyajian的帮助。这就是我的所作所为。

已安装的离子源

文件传输和文件插件
this.platform.ready().then(() => {

      const fileTransfer: FileTransferObject = this.transfer.create();
      const pdfLocation = this.pdffile;//pdffile is the PDF URL which we got as the response from the generatePDF API

      fileTransfer.download(pdfLocation, this.storageDirectory + "filename.pdf").then((entry) => {
        const alertSuccess = this.alertCtrl.create({
          title: `Download Succeeded!`,
          subTitle: `PDF was successfully downloaded to: ${entry.toURL()}`,
          buttons: ['Ok']
        });

        alertSuccess.present();

        this.file.readAsDataURL(this.storageDirectory, 'filename.pdf')
        .then((datafile) =>{
          this.attachpdf(id,datafile);
        })
        .catch((err) =>{
          console.log("Error is that "+err);
        });

      }, (error) => {

        const alertFailure = this.alertCtrl.create({
          title: `Download Failed!`,
          subTitle: `PDF was not successfully downloaded. Error code: ${error.code}`,
          buttons: ['Ok']
        });
        alertFailure.present();
      });
    });

使用了一个函数(我从搜索中获得)将base64data转换为blob。

    public dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
 }

然后,

    public attachpdf(emailid,filetoattach){
     let headers = new Headers();
    headers.append(...);
    headers.append('enctype','multipart/form-data');

    var blob = this.dataURItoBlob(filetoattach);

    var data ={... };

    var formData = new FormData();
    formData.append("data",JSON.stringify(data));
    formData.append("doc",blob);

    this.http.post('sendMail API',formData, {headers: headers})
    .map(res => res.json())
    .subscribe(results => { 
      ...
    },
    error=>{
      ..
    }
    )
  }

它终于奏效了。

相关问题