图片上传/接收API [英] Image upload/receive API

查看:39
本文介绍了图片上传/接收API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to offer a simple API on my website that allows people to upload images to it (and receive the URL to access it).

但我有几个问题:

  • 如果用户必须以二进制代码发送图像会更好还是如果用户必须以 idk ASCII 左右发送图像会更好?什么是常规方式?(我这么问是因为我可以想象某些语言只有将文件作为文本文件读取的功能.)

  • Would it be better if the user would have to send the image in binary code or would it be better if the user would have to send it in idk ASCII or so? What is the conventional way? (I'm asking that because I can imagine that some languages only have functions to read files as textfiles.)

我将图像存储在服务器的什么位置以及如何存储?我可以将它们放在 MySQL 数据库中并且性能良好吗?还是应该将它们全部放在一个文件夹中?

Where do I store the images on the server and how? Can I put them in a MySQL database and would that perform well? Or should I put them all in one folder?

用户应该如何指定文件类型?在标题中还是在正文中?

How should the user be able to specify the file type? In the header or in the body?

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

How do I receive and the data save it as a file?

我在别处找到了这个代码:

I found this code somewhere else:

<?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 数据"是个好主意吗?

Does this work for binary files like images?
Is it a good idea to "Read the data 1 KB at a time"?

推荐答案

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

The easiest way is to store the file in a folder on your server. Then store the URL of the file in a MySQL Database, and pull the file URL (assuming you have a login function) if the user does not know the file location.

例如:

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

(UPLOAD.PHP or the script you are using to upload the file to your server)

<?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";
    }
?>

现在您可以做的是在页面中创建一个表格,并根据登录者列出所有上传的文件(同样,假设您使用此功能).这将允许此人知道必须保留他们上传的所有文件的日志.

Now what you can do is make a table in a page, and have it list all the uploaded files based on who is logged in (again, assuming you use this feature). This will allow the person to know have to keep a log of all the files they upload.

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

The following example is if you are posting the data using Ajax, and it returns the JSON formatted data, so you can have the user not have to reload the page.

<?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 you would also like to restrict the file size, you can add a simple line of code that will also check for the file size, and if it is to big, won't let it go through:

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)) {

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

If you need any more help, feel free to let me know. :)

这篇关于图片上传/接收API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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