PHP JavaScript下载base64文件,电子邮件附件

时间:2018-10-08 20:38:00

标签: javascript php jquery base64 gmail-api

我试图从使用GmailApi构建的仪表板上的电子邮件中获取附件,作为文件。现有代码适用于某些附件,但对于某些附件却存在错误(chrome):下载失败-网络错误。 有一个前端代码:

$('a.email-attachment').click(function(e){
    var url="<?php echo ($getAttachment); ?>";
    url=url.replace(/amp;/g,'')
    e.preventDefault()
    var attachmentId=$(this).attr('data-attachmentId')
    var fileName=$(this).attr('data-fileName')
    var fileSize=$(this).attr('data-fileSize')
    var mimeType=$(this).attr('data-mimeType')
    var messageId=$(this).parents('.email-single').attr('data-messegaId');
    var email=$(this).parents('.email-tab').attr('data-email')
    if(fileSize>30000000){
        alert('This file is too big use gmail');
        return
    }
    var data={
        'attachmentId':attachmentId,
        'messageId':messageId,
        'email':email,
    }
    jQuery.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function (resp) {
            var file='data:'+mimeType+';base64,' + resp;
            var link = document.createElement('a');
            link.download = fileName;
            //link.href = 'data:,' + resp;
            link.href = file;
            document.body.appendChild(link);
            link.click();
        }
    })
})

有用于后端的代码:

public function getAttachment()
{
    // retrieve stuff works ok
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    require_once __DIR__ . '/vendor/autoload.php';

    $attachmentId=$this->request->post['attachmentId'];
    $messageId=$this->request->post['messageId'];
    $email=$this->request->post['email'];

    $key = array_search($email, array_column($this->details,'email'));
    if($this->details[$key]['email']!=$email){
        //echo $email;
        return 0;
    }
    $detail=$this->details[$key];

    $client = $this->getClient($detail['redirect_url'],$detail['app_name'],$detail['secret'],$detail['credentials']);
    $service = new Google_Service_Gmail($client);
    $single_attachment = $service->users_messages_attachments->get('me',$messageId, $attachmentId);
    //end of the retrieve stuff
    $data=strtr($single_attachment->getData(),'-_', '+/');
    //$data=str_replace('-_', '+/',$single_attachment->getData());
    echo $data;


}

该错误主要发生在大文件上,并且仅在浏览器(而非前端)中发生。我总是在响应中得到一些base64字符串,而不会发出警告或错误。

我该如何解决?我建议这可能与PHP设置有关,或者我错过了这一行。

$data=strtr($single_attachment->getData(),'-_', '+/');

enter image description here

0 个答案:

没有答案