我計劃開發一個圖像上傳API,它需要將圖像上傳到服務器位置作爲我的項目的一部分。 (用法是使用Android應用程序上傳用戶圖片和頭像)使用博客將圖像上傳到服務器PHP
API應與Imgur API類似,我們可以在其中使用發佈請求將二進制圖像上傳到服務器。
我通過多個問題搜索,所有得到的是使用多部分請求,這需要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
}
}
?>
它有效的語法'!! $ _ FILES ['file'] ['tmp_name']'??雙'!!' – Saty
哎呀。糾正它。感謝您的信息。 –
等待'!!'我認爲實際上更有意義,現在你似乎只在沒有文件上傳時才運行驗證碼。雙重exclam'!!'只是簡單地將一個值轉換爲布爾值,因爲它僅僅意味着虛假行爲。因此,它將採用一個變量並評估它的布爾值,然後應用邏輯「NOT」,再次執行該操作只會將一個變量轉換爲布爾值,但由於它處於if條件,因此無論如何,所以我不在這裏看點。但是,編輯後,它實際上看起來是錯誤的。 – apriede