How to pass an image in HTTP POST request and insert into a Database Table

折月煮酒 提交于 2019-12-10 23:56:27

问题


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:


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.



来源:https://stackoverflow.com/questions/11590630/how-to-pass-an-image-in-http-post-request-and-insert-into-a-database-table

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