Image upload/receive API

你说的曾经没有我的故事 提交于 2021-02-18 07:34:08

问题


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

But I have several questions:

  • 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.)

  • 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);

?>

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


回答1:


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.

For instance:

(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.

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. :)




回答2:


I would also recommend to use fileinfo or even some libraries like imagemagic to be sure that image is an image - and if it is convert it to the ones that can be shown on page.

Also because you check file size after it was already sent to server, you can check if you can convert its size to be smaller instead of just rejecting it.

PS: http://www.plupload.com/ this is library that you can user free or with small one time fee - it also have some php written receiver for itself.




回答3:


You can encode_base64 the raw php input - image file - and store in a mysql row which is ASCII BIN, LONG TEXT structure, and then pull the data back from mysql and show like this:

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



回答4:


The upload method that Brian's answer mentioned is a ideal solution. And it is easy to store the pictures. You should create a table in the db of your server and to store the file name of the picture, for example, as format of "filename.+filetype". Then store the pictures in some folder of server.

You don't need to store the whole path of the picture like www.xxx.com/upload/temp/1.png, try to use a php function to create the absolute path for www.xxx.com/upload/temp/, then once you want to show the picture. Just use

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

func() is a function that create the absolute path.

For more information, you could check w3c tutorial PHP file upload

I use this way in my website. Hope it could help you.




回答5:


You're thinking too low-level

Your API really ought to be built atop some other protocol that has already solved presentational issues of this sort.

Over HTTP, for example, one would just transmit the file in its raw binary form—sure, one can specify in the protocol headers that an encoding has been applied to the content or the transfer, but pretty much only compression encodings (that result in yet more binary) are supported.



来源:https://stackoverflow.com/questions/23232766/image-upload-receive-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!