图片上传/接收API

时间:2014-04-23 00:35:17

标签: php mysql api upload

我想在我的网站上提供一个简单的API,允许人们上传图像(并接收访问它的URL)。

但我有几个问题:

  • 如果用户必须以二进制代码发送图像,或者如果用户必须以idk ASCII格式发送它,那会更好吗?传统方式是什么? (我问的是因为我可以想象某些语言只有将文件作为文本文件读取的功能。)

  • 我在哪里将图像存储在服务器上以及如何存储?我可以把它们放在MySQL数据库中,那会表现不错吗?或者我应该将它们全部放在一个文件夹中?

  • 用户应该如何指定文件类型?在标题或身体?

  • 如何接收数据并将其另存为文件?

我在其他地方找到了这段代码:

<?php

/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);

?>

这适用于像图像这样的二进制文件吗? “一次读取数据1 KB”是个好主意吗?

5 个答案:

答案 0 :(得分:2)

最简单的方法是将文件存储在服务器上的文件夹中。然后将文件的URL存储在MySQL数据库中,如果用户不知道文件位置,则拉出文件URL(假设您有登录功能)。

例如:

(UPLOAD.PHP或用于将文件上传到服务器的脚本)

<?php
    $connect_to_db = mysqli_connect('localhost', 'user', 'pass', 'db');

    $user = $_POST['user'];

    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && in_array($extension, $allowedExts)) {

      if ($_FILES["file"]["error"] > 0) {

        echo "Error: " . $_FILES["file"]["error"] . "<br>";

      } else {

        //Move the file to the uploads folder
        move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);

        //Get the File Location
        $filelocation = 'http://yourdomain.com/uploads/'.$_FILES["file"]["name"];

        //Get the File Size
        $size = ($_FILES["file"]["size"]/1024).' kB';

        //Save to your Database
        mysqli_query($connect_to_db, "INSERT INTO images (user, filelocation, size) VALUES ('$user', '$filelocation', '$size')");

        //Redirect to the confirmation page, and include the file location in the URL
        header('Location: confirm.php?location='.$filelocation);
      }
    } else {
      //File type was invalid, so throw up a red flag!
      echo "Invalid File Type";
    }
?>

现在你可以做的是在一个页面中创建一个表,让它根据登录的人列出所有上传的文件(再次假设你使用这个功能)。这将使该人知道必须记录他们上传的所有文件。

以下示例是您使用Ajax发布数据,并返回JSON格式的数据,因此您可以让用户不必重新加载页面。

<?php
    $connect_to_db = mysqli_connect('localhost', 'user', 'pass', 'db');

    $user = $_POST['user'];

    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && in_array($extension, $allowedExts)) {

      if ($_FILES["file"]["error"] > 0) {

        echo json_encode(array('status' => 'error', 'msg' => 'File could not be uploaded.'));

      } else {

        //Move the file to the uploads folder
        move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);

        //Get the File Location
        $filelocation = 'http://yourdomain.com/uploads/'.$_FILES["file"]["name"];

        //Get the File Size
        $size = ($_FILES["file"]["size"]/1024).' kB';

        //Save to your Database
        mysqli_query($connect_to_db, "INSERT INTO images (user, filelocation, size) VALUES ('$user', '$filelocation', '$size')");

        //Return the data in JSON format
        echo json_encode(array('status' => 'success', 'data' => array('filelocation' => $filelocation, 'size' => $size)));
      }
    } else {
      //File type was invalid, so throw up a red flag!
      echo json_encode(array('status' => 'error', 'msg' => 'Invalid File Format'));
    }
?>

如果你还想限制文件大小,你可以添加一行简单的代码来检查文件的大小,如果它很大,就不会让它通过:

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000) //Must be smaller than 20KB
&& in_array($extension, $allowedExts)) {

如果您需要更多帮助,请随时告诉我。 :)

答案 1 :(得分:1)

我还建议您使用fileinfo甚至某些类似imagemagic的库来确保图片是图片 - 如果将图片转换为可以在页面上显示的图片。< / p>

另外,因为您在已经将文件大小发送到服务器之后检查文件大小,您可以检查是否可以将其大小转换为更小而不是仅仅拒绝它。

PS:http://www.plupload.com/这是你可以免费或少付一次费用的图书馆 - 它也有一些自己编写的php接收器。

答案 2 :(得分:1)

您可以encode_base64原始php输入 - 图像文件 - 并存储在一个mysql行中,该行是ASCII BIN,LONG TEXT结构,然后从mysql中提取数据并显示如下:

<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

答案 3 :(得分:1)

Brian的回答提到的上传方法是一个理想的解决方案。并且很容易存储图片。您应该在服务器的数据库中创建一个表,并存储图片的文件名,例如,格式为“filename。+ filetype”。然后将图片存储在服务器的某个文件夹中。

您不需要存储图片的整个路径,如www.xxx.com/upload/temp/1.png,尝试使用php函数为www.xxx.com/upload创建绝对路径/ temp /,然后一旦你想要显示图片。只需使用

<img src="<?php echo func("1.png")?>" alt=""> 

func()是一个创建绝对路径的函数。

有关详细信息,请查看w3c教程PHP file upload

我在我的网站上使用这种方式。希望它可以帮到你。

答案 4 :(得分:1)

你的想法太低了

你的API确实应该建立在已经解决了这类表现问题的其他协议之上。

通过HTTP,例如,人们只会以原始二进制形式传输文件 - 确保一个可以在协议标头中指定编码已应用于内容或传输,但几乎只支持压缩编码(导致更多二进制)。