如何在HTTP POST请求中传递图像并插入到数据库表中 [英] How to pass an image in HTTP POST request and insert into a Database Table

查看:310
本文介绍了如何在HTTP POST请求中传递图像并插入到数据库表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将表单值检索到 insert.php 文件,以便将它们存储在数据库中。但是,表单中的一个元素是文件选择器对话框,用于以JPG或其他文件格式上传图像文件。



我在网上发现了这段代码,通过发布请求发送图片,但无法让它正常工作。

  $ PIC =($ _ FILES [ '相片'] [图像']); 

它只显示文件的名称,而不显示实际的文件本身$ b $首先,你需要在HTML表单中添加 enctype 属性。像这样:

 < form action =page.phpmethod =postaccept-charset =utf-8 enctype =multipart / form-data> 
< input type =filename =photoid =photo/>
< input type =submitvalue =上传/>
< / form>

接下来,当这将在下一页发送时,使用 $ _ FILES 全局数组,而不是 $ _ POST 数组检索图像。

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

使用 $ _ POST发送所有文本数据但文件将使用 $ _ FILES



编辑:传输如果您进一步想要在表中插入这个上传的数据(虽然这是从来没有推荐过的,并且是一个巨大的性能损失)

  $ image = file_get_contents(/var/www/image.jpg); 
$ image = addslashes($ image);
...
$ sql =插入图片(图片)VALUES('。$ image。');
//剩余的MySQL和PHP代码

注意:我正在考虑将 / var / www 作为我的web文件夹,它在Linux机器上配置为默认 localhost


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

解决方案

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.

这篇关于如何在HTTP POST请求中传递图像并插入到数据库表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆