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

查看:70
本文介绍了图片上传/接收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天全站免登陆