我有这段代码可以工作:
session_start();
if ( isset($_SESSION['username']) ) {
$params = explode(".", basename($_FILES["file"]["name"]));
$target = array_values($params)[0];
$id = array_values($params)[1];
if ( ($target == "profile") || ($target == "question" && $_SESSION["waitingImagesQuestion"] > 0) || ($target == "answerswer" && $_SESSION["waitingImagesAnswer"] > 0) ) {
$imageDirectory = "images/".round(microtime(true)*1000).".png";
if ( move_uploaded_file($_FILES["file"]["tmp_name"], $imageDirectory) ) {
print "success";
}
}
}
print JsonBuilder::getStringError();
现在我想要与symfony做同样事情的代码。我该怎么写?
谢谢
有一个关于 Symfony.com 的食谱项目解释了如何上传文件。看看 http://symfony.com/doc/current/cookbook/controller/upload_file.html 和/或 http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html。
要获取会话变量(如用户名),您可以使用控制器中的session
服务:
$this->get('session')->get('username');
对于会话,您可以使用 $this->getUser()
对于上传 mabe 此链接很有帮助http://symfony.com/doc/current/cookbook/controller/upload_file.html
这段代码有效!
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Symfony'Component'HttpFoundation'Response;
class SendImage extends Controller {
/**
* @Route("/apprequests/SendImage")
*/
public function numberAction() {
$jsonManager = $this->get('epb.JsonManager');
$session = $this->get('session');
if ( $session->isStarted() ) {
$params = explode(".", basename($_FILES["file"]["name"]));
$target = array_values($params)[0];
$id = array_values($params)[1];
if ( ($target == "profile") || ($target == "question" && $session->get('waitingImagesQuestion') > 0) || ($target == "answerswer" && $session->get('waitingImagesAnswer') > 0) ) {
$imageName = round(microtime(true)*1000).".png";
$imageDirectory = "images/".$imageName;
if ( move_uploaded_file($_FILES["file"]["tmp_name"], $imageDirectory) ) {
print "success";
}
}
}
else {
return new Response($jsonManager->getStringError());
}
}