我计划开发一个图像上传 API,作为我项目的一部分,它需要将图像上传到服务器位置。 (用途是使用Android应用程序上传用户图片和头像)
API应该类似于Imgur API其中我们可以使用 post 请求将二进制图像上传到服务器。
我搜索了多个问题,得到的都是使用多部分请求,需要 html 表单提交。由于我的目标是创建一个 API,因此 html 表单提交将是不可能的。
无论如何,我提交了一个使用 html 表单上传图像的示例代码。有人可以告诉我如何修改脚本以满足我的要求吗?
<html>
<body>
<form action="photo.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP 代码
<?php
$allow = array("jpg", "jpeg", "gif", "png");
$todir = 'uploads/';
if (!!$_FILES['file']['tmp_name'] ) // is the file uploaded yet?
{
$info = explode('.', strtolower( $_FILES['file']['name']) ); // whats the extension of the file
if ( in_array( end($info), $allow) ) // is this file allowed
{
if ( move_uploaded_file( $_FILES['file']['tmp_name'], $todir . basename($_FILES['file']['name'] ) ) )
{
// the file has been moved correctly
}
}
else
{
// error this file ext is not allowed
}
}
?>
最佳答案
关于服务器端代码的一些注释(排名不分先后):
正如您可以在 Handling file uploads 中阅读的那样,验证上传的正确方法是将
['error']
子项与UPLOAD_ERR_OK
( codes explained here ) 进行比较。不要为此使用['tmp_name']
。不要让最终用户选择服务器上的实际文件名。您最好自己生成一个唯一的名称,并将显示名称保留在其他地方(例如数据库)
确定文件扩展名的推荐方法是 pathinfo :
pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)
用户提供的文件扩展名并不是确定文件类型的可靠方法。对于图片,getimagesize函数经常被使用。
关于php - 使用 post PHP 将图像上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37392907/