将图片上传到MYSQL数据库&使用PHP和Swift来显示它 [英] Upload image in MYSQL database & display it using PHP with Swift

查看:110
本文介绍了将图片上传到MYSQL数据库&使用PHP和Swift来显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题陈述::我正在使用Swift和amp;的POST请求在MYSQL数据库中上传图像. PHP.我可以在数据库中插入选定的图像.但无法显示它.

Problem Statement : I'm uploading images in MYSQL database using POST request with Swift & PHP. I'm able to insert selected image in database. But unable to display it.

MYSQL表格式:

现在我正在将这些图像从数据库显示到我的本地主机.这给我的结果如下...

And now I'm displaying this images from database to my localhost. Which gives me result as follows...

快速文件:

@IBAction func uploadOnServer(sender: AnyObject)
{
    if Description.text == "" || imageView.image == nil
    {

    }
    else
    {
        let img:UIImage = imageView.image!

        let request = NSMutableURLRequest(URL:NSURL(string: "http://localhost/RESTAPI/UploadImage.php")!)
        request.HTTPMethod = "POST"

        let postString = "img=\(img)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
        {
            data, response, error in
            print("response =\(response)")

            if error != nil
            {
                print("error=\(error)")
                return
            }
        }
        task.resume()
        Description.text = ""
        imageView.image = nil

    }
}

PHP文件:

<?php

    $host = "localhost";
    $username = "scott";
    $password = "tiger";
    $dbname = "mydb";

    $link = mysqli_connect($host, $username, $password, $dbname);
    $arr = array();

     if($link == true)
    {
        //Displaying images from mysql 
        $select_image="select * from images";// where id=1";

        $var=mysqli_query($link,$select_image);

        echo "<table>";
        while($row=mysqli_fetch_array($var))
        {
            //$desc = $row["Description"];
             $img = $row['image'];

              echo "<tr>";//<td><b>$desc</b></td>";
              echo "<td><img src = '$img' width = 100 height = 100></td></tr>";
        }
    }
    else
    {
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }


    if($_SERVER['REQUEST_METHOD'] == "POST")
    {
        $img = $_REQUEST['img'];
        $sql1 = "INSERT INTO images (image) VALUES ('$img')";
        if(mysqli_query($link, $sql1))
        {
            echo "Image added successfully.";
        } 
        else
        {
            echo "ERROR: Could not able to execute $sql1.mysqli_error($link)";
        }
    }

mysqli_close($link);
?>

推荐答案

从用户那里获取图片

请参见 http://php.net/manual/en/reserved. variables.files.php http://php.net/manual/zh-cn/features.file-upload.php 和朋友了解如何使用$_FILES接收上载的数据.

See http://php.net/manual/en/reserved.variables.files.php and http://php.net/manual/en/features.file-upload.php and friends for the datails of how to use $_FILES to receive the uploaded.

将图像包含在变量中后,例如$jpg,请勿使用任何文本编码/解码功能;它只会弄乱东西.下面的不同方法将说明如何避免跳入8位代码.

Once you have the image in a variable, say $jpg, do not use any text encode/decode functions; it will only mangle things. The different approaches below will say what to do to avoid tripping over 8-bit codes.

有三种显示图像的方法,每种方法都有些复杂

将图像存储在数据库中;内嵌显示图片

我已将这种方法用于缩略图,但不建议用于大图像.

I have used this approach for thumbnails, but don't recommend for big images.

将其存储在表的MEDIUMBLOB中,在PHP中使用bin2hex()将图像转换为字符串.然后使用INSERT ... VALUES (UNHEX('...'))在MySQL服务器端切换回二进制文件.

Store it in a MEDIUMBLOB in a table, use bin2hex() in PHP to turn the image into a string. Then use INSERT ... VALUES (UNHEX('...')) to switch back to binary at the MySQL server side.

重新加载后,让引用的PHP说出类似的内容

After reloading, have the referencing PHP say something like

$b64 = base64_encode($blob);
echo "<img src='data:image/jpeg;base64,$b64'/>";

将图像存储在数据库中; PHP脚本生成图像

当我想使用PHP的图像*"功能在显示图像之前对其进行修改时,可以使用此功能.因为这比您可能需要的更多,所以我只会略过需要做的事情.

I use this when I want to use PHP's "image*" functions to modify the image before displaying it. Since this is more involved than you probably need, I will only skim over what needs doing.

该页面的html会使用所需的任何参数调用另一个脚本:

The html for the page would invoke another script, with whatever arguments you need:

<img src=modify.php?this=stuff&that=stuff>

然后从modify.php开始,

header('Content-type: image/jpeg');

并以此结尾(假设您正在构建JPEG):

And end with this (assuming you are building a JPEG):

imagejpeg($im);

将图像存储在文件中

这是大多数大型网站大部分时间首选的方式.

This is the preferred way that most of the big web sites do it most of the time.

如果您的文件来自上载,则类似这样的操作会将其移至更好的路径,而无需触摸jpg.

If your file comes from an upload, then something like this moves it to a better path without having to touch the jpg.

$tmpfile = $_FILES['userfile']['tmp_name'];
move_uploaded_file($tmpfile, $uploadfile);

更多信息和示例: http://php.net/manual/zh-CN/function.move-uploaded-file.php

在HTML中,只需生成如下内容:

In the HTML, simply generate something like this:

<img src=path/to/file>

对可以放置图像的服务器路径进行一些研究,并确保权限足够.

Do some research on where in your server's path you can put images, and make sure the permissions are adequate.

注意:数据库不参与保存图像,而是具有用于保存URL "path/to/file"的列:

Note: The database is not involved in holding the image, instead it has a column for holding the url "path/to/file":

image VARCHAR(255) NOT NULL

以供进一步讨论

  • 您想深入研究三种技术中的哪一种?
  • 让我们看看您生成的HTML.
  • 让我们看看SHOW CREATE TABLE.

这篇关于将图片上传到MYSQL数据库&amp;使用PHP和Swift来显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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