weixin_33701251 2015-03-07 06:14 采纳率: 0%
浏览 30

在AJAX处理程序中下载文件

I wrote a small script using only PHP to test file download functionality using a experimental API, where this worked fine. When I decided to commit this code to my project, I added the same code to the handler for my AJAX call, however it does not start the download as it did before.

I believe this is due to the fact I am using AJAX, however as I was using header() to initiate the file download on the client, I am at a loss as to how to work around this.

Can anyone suggest an alternative method to do this now?

AJAX:

    $.ajax({
        type: "POST",
        url: "handler.php",
        data: { 'action': 'downloadFile', 'filename': curSelectedFile },
        dataType: 'json',
        success: function(data)
        {
            //Success
        }
    });

PHP Handler:

case "downloadFile":
{
    $filename = '';

    if (isset($_POST["filename"]))
    {
        $filename = $_POST["filename"];
    }

    $pos = 0; // Position in file to start reading from
    $len = 32; // Length of bytes to read each iteration
    $count = 0; // Counter for the number of bytes in the file

    do
    {
        $result = $fm->getFileChunk($filename, $pos, $len);
        $chunk = $result->result;

        if (!empty($chunk))
        {
            $chunk = base64_decode($chunk);
            $count += strlen($chunk);

            echo $chunk;
        }

        $pos += $len;
    }
    while (!empty($chunk));

    header('Content-Disposition: attachment; filename="'. $filename .'"');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . $count);

    $response['status'] = "success";

    echo json_encode($response);

    break;
}
  • 写回答

1条回答 默认 最新

  • weixin_33705053 2015-03-07 06:29
    关注

    You can encode your file in base64 and create File Object using JavaScript.

    I wouldn't recommend this for large files!

    Alternative:

    Save your file on server and you can just retrieve file location and redirect using location.href in Ajax callback.

    You can decode base64 using atob() and create typed array. refer to following link for creating Binary Object on client side. You create typed array like answered here.

    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败