Trying to download Blob via PHP / MySQL

你说的曾经没有我的故事 提交于 2019-12-18 06:58:27

问题


This is one I just can't figure out: I have successfully built an upload feature on a web page to upload files to a MySQL Database. When I go on the server and open them via phpMyAdmin, they all look fine... txt, jpg, pdf, etc.

Yet, after putting together THIS thing (below) to download it, I get a strange problem: All of the text documents (and all other types of files, after I change the extension to 'txt') contain HTML code of the page itself, followed by the original content!

Also, different browsers display differently after the POST. When trying to download a txt file, IE will show the correct data in the ECHO on the page itself (no downloading) with an error message just before it:

Warning: Header may not contain more than a single header, new line detected. in C:\wamp\www\ace\dmain.php on line 82.

Line 82 is 'header("Content-length...'

Neither Firefox nor Chrome show anything. They just allow me to download it.

Here's the code:

<?php
if (isset($_POST['downloadid'])) {
    $fileid = $_POST['downloadid'];
    try {
      $sql = "SELECT * FROM `datastore` WHERE `id` = '".$fileid."'";
        $results = $pdo->query($sql);echo $sql;
        while ($row = $results->fetch()) {
            $filename = $row['filename'];
            $mimetype = $row['mimetype'];
            $filedata = $row['filedata'];
            header("Content-length: strlen($filedata)");
            header("Content-type: $mimetype");
            header("Content-disposition: download; filename=$filename"); //disposition of download forces a download
            echo $filedata; 
            // die();
        } //of While
    } //try
    catch (PDOException $e) {
        $error = '<br>Database ERROR fetching requested file.';
        echo $error;
        die();    
    } //catch
} //isset
?>

回答1:


This:

header("Content-length: strlen($filedata)");

Is not going to produce what you expect. If you look at the headers in wireshark, or another method to view the request you will see that it does not contain an integer.

Use this instead:

header("Content-length: ".strlen($filedata));



回答2:


After agonizing over fixing it in-place (that is, on the same page with the rest of the html and code), I decided to move it to a dedicated PHP page. After that, it worked fine.

Thanks for the comments!




回答3:


here is good example and complete source



来源:https://stackoverflow.com/questions/15009672/trying-to-download-blob-via-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!