drh96824 2012-07-21 08:20
浏览 147
已采纳

如何在HTTP POST请求中传递图像并插入数据库表

I need to retrieve form values to insert.php file in order to store them in the database. However one of the elements in the form is a file chooser dialog to upload an image file in JPG or other file format.

I found this code online to send the image via a post request, but cannot get it to work correctly

$pic=($_FILES['photo'][image']); 

It only displays the name of the file and not the actual file itself

  • 写回答

1条回答 默认 最新

  • dongxiaolin2801 2012-07-21 08:42
    关注

    First of all you need to add the enctype attribute to your HTML form. Like this:

    <form action="page.php" method="post" accept-charset="utf-8" enctype="multipart/form-data">
        <input type="file" name="photo" id="photo" />
        <input type="submit" value="Upload" />
    </form>
    

    Next, when this will be sent on the next page use the $_FILES global array instead of the $_POST array to retrieve the image.

    <?php
        move_uploaded_file( $_FILES['photo']['tmp_name'], "/var/www/image.jpg" );
        echo("<img src='image.jpg'");
    ?>
    

    All text data will be sent using $_POST but the file will be transferred using $_FILES.

    Edit: If you further want to insert this uploaded data in the table (although this is never recommended and is a huge performance loss)

    $image = file_get_contents( "/var/www/image.jpg" );
    $image = addslashes( $image );
    ...
    $sql = "INSERT INTO pictures(image) VALUES('" . $image . "')";
    //remaining MySQL and PHP code
    

    Note: Here I am considering /var/www as my web folder which is configured as default localhost on Linux machines.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据