dreljie602951 2019-06-11 22:10
浏览 116

从PHP下载excel文件

I am working in a project where I store files in Mysql database.

I stored the files as long blob in my database and I want to make them readable in my site web based on PHP. I tried to view PDF files and it works but if I try to download Excel File, it gives me file.php and some numbers.

//PHP

$dbh= new PDO("mysql:host=localhost;dbname=smi","root","");
$id=isset($_GET['id_fichier'])? $_GET['id_fichier']:"";
$stat=$dbh->prepare("select * from fichier where id_fichier=?");
$stat->bindparam(1,$id);
$stat->execute();
$row=$stat->fetch();
$file = $row['fichier'];
$type=$row['type'];
header('Content-Type:'.$type);
echo($file);

I expect the excel file but I get something like this.

3c21 444f 4354 5950 4520 6874 6d6c 3e0d
0a3c 6874 6d6c 2064 6972 3d22 6c74 7222
206c 616e 673d 2265 6e22 3e0d 0a3c 6865
6164 3e0d 0a3c 7469 746c 653e 534d 4920
4165 726f 706f 7274 2046 6573 2053 6169
7373 3c2f 7469 746c 653e 0d0a 0d0a 3c2f
  • 写回答

1条回答 默认 最新

  • duanpo8329 2019-06-11 22:43
    关注

    Make sure you have added it correctly into your database and that the type of the column fichier is set to BLOB and not anything else.

    Here's a clean code to insert it into your database:

    $dbh = new PDO('mysql:host=localhost;dbname=smi', 'root', '');
    
    $file = 'XYZ.xls';
    $blob = fopen($file, 'rb');
    $mime = 'application/vnd.ms-excel';
    
    $sql  = "INSERT INTO `fichier` (fichier, type) VALUES (:fichier, :type)";
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':fichier', $blob, PDO::PARAM_LOB);
    $stmt->bindParam(':type', $mime);
    $stmt->execute();
    

    And then select it back:

    if(isset($_GET['id_fichier'])){
       $id   = $_GET['id_fichier'];  
       $stmt = $dbh->prepare("SELECT * from `fichier` where `id_fichier` = :id");
       $stmt->bindColumn(':id', $id);
       $stmt->execute();
    
       $data = $stat->fetch();
       $file = $data['fichier'];
       $type = $data['type'];
       header('Content-Type:'.$type);
       echo($file);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)