php - 图片上传/接收API

标签 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 的数据”是个好主意吗?

最佳答案

最简单的方法是将文件存储在服务器上的文件夹中。然后将文件的 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)) {

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

关于php - 图片上传/接收API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232766/

相关文章:

php - 在 php 中上传 docx、zip、rar、pdf、ppt

php - 特殊字符问题

ruby-on-rails - API 参数中的连字符

c++ - Ubuntu中如何通过语音命令生成键盘、鼠标事件

java - 如何在响应对象中设置状态码400

php - 如何把一段文本中的所有图片放到一个数组中,PHP?

php - 为什么我的图像翻转会这样?

php - 使用 PHP 选择并配对两个用户

php - 使用 mysqli_escape_string 函数出错

java - 使用 JAVAFx 更新和删除不适用于 mysql 数据库