composer require codeguy/upload
建立 ZM\AdminBundle\Controller\DefaultController 並實作 uploadPic() 方法:
namespace ZM\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;
class DefaultController extends Controller
{
/**
* 上傳圖片並以使用者 ID 命名
* @param string $user_id 使用者 ID
* @param string $str 表單 file 欄位 name
* @param string $path 儲存相對路徑
* @return string|bool 成功回傳檔名(含副檔名),失敗回傳 false
*/
public function uploadPic($user_id, $str, $path)
{
$fs = new Filesystem();
if (!$fs->exists($path)) {
$fs->mkdir($path, 0700);
}
$storage = new \Upload\Storage\FileSystem($path);
$file = new \Upload\File($str, $storage);
if ($file->getName() !== '') {
$file->setName($user_id); // 以 user_id 為檔名
$file->addValidations(array(
new \Upload\Validation\Mimetype(array('image/png','image/jpg','image/jpeg','image/gif')),
new \Upload\Validation\Size('2M')
));
try {
$file->upload();
return $file->getNameWithExtension();
} catch (\Exception $e) {
// 可記錄 $file->getErrors()
return false;
}
}
return false;
}
}
namespace ZM\ApiBundle\Controller;
use ZM\AdminBundle\Controller\DefaultController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ContactController extends BaseController
{
public function uploadHeadAction()
{
$request = Request::createFromGlobals()->request;
$user_id = $request->get('user_id');
if (!isset($_FILES['head']) || $_FILES['head']['error'] !== UPLOAD_ERR_OK) {
return new Response(json_encode([
'flag' => 2,
'content' => '未選擇圖片或上傳錯誤'
]), 200, ['Content-Type' => 'application/json']);
}
$conn = $this->getDoctrine()->getConnection();
$data = $conn->fetchAssoc("SELECT id, head FROM contact WHERE id = ? LIMIT 1", [$user_id]);
if (empty($data['id'])) {
return new Response(json_encode([
'flag' => 3,
'content' => '使用者不存在'
]), 200, ['Content-Type' => 'application/json']);
}
$path = 'image/head/';
$file_name = $this->uploadPic($user_id, 'head', $path);
if ($file_name) {
$conn->executeUpdate("UPDATE contact SET head = ? WHERE id = ?", [$path . $file_name, $user_id]);
return new Response(json_encode([
'flag' => 1,
'content' => '上傳成功'
]), 200, ['Content-Type' => 'application/json']);
}
return new Response(json_encode([
'flag' => 0,
'content' => '上傳失敗'
]), 200, ['Content-Type' => 'application/json']);
}
}
/image/head/{user_id}.jpg。open_basedir、禁用腳本執行權限