[symfony2中文手册]Symfony2利用Upload实现图片上传例子

更新时间:2019-11-17    来源:Symfony    手机版     字体:

【www.bbyears.com--Symfony】

我们在应用程序或者网站的个人资料里一般都有设置头像的功能,这一章我们在Symfony2里用第三方的一个比较有名Upload库来制作上传图片的功能。

一、安装第三方库

1.在composer.json文件中的”require”中加入

"codeguy/upload": "*"
composer

2.运行指令安装


composer update

二、编码

1.编写uploadPic方法上传图片,并将上传图片的用户id作为文件名

 

namespace ZM\AdminBundle\Controller;
 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;
 
class DefaultController extends Controller {
 
    public function indexAction($name) {
        return $this->render("ZMAdminBundle:Default:index.html.twig", array("name" => $name));
    }
 
    /**
     * 上传图片
     *
     * @param type $user_id 用户的id,用作文件名
     * @param type $str     表单中file类型的input的name
     * @param type $path    保存路径
     * @return type
     */
    public function uploadPic($user_id, $str, $path) {
 
        $fs = new Filesystem();
 
        //检查路径是否存在
        if (!$fs->exists($path)) {
            //如果不存在,创建目录
            $fs->mkdir($path, 0700);
        }
 
        //使用Upload库
        $storage = new \Upload\Storage\FileSystem($path);
        $file = new \Upload\File($str, $storage);
 
        //如果文件名为空
        if ($file->getName() != "") {
            //设置文件名为用户的id
            $file->setName($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();
                //文件名和扩展名
                $file_name = $file->getNameWithExtension();
            } catch (\Exception $e) {
                //失败!
                $errors = $file->getErrors();
            }
        }
 
        //返回文件名和扩展名
        return $file_name;
    }
 
}

2.用户上传头像,并将头像全路径存入数据库


 

namespace ZM\ApiBundle\Controller;
//引用写好的上传图片方法uploadPic的Controller,并命名为BaseController
use ZM\AdminBundle\Controller\DefaultController AS BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
//继承BaseController
class ContactController extends BaseController {
 
    /**
     * 用户上传头像
     *
     * @return Response
     */
    public function uploadHeadAction() {
 
        $request = Request::createFromGlobals()->request;
        $user_id = $request->get("user_id");
 
        //判断是否有文件上传
        if (isset($_FILES["head"]) && $_FILES["head"] != "") {
 
            $conn = $this->getDoctrine()->getConnection();
            $data = $conn->fetchAssoc("SELECT id, head FROM contact WHERE id = ? LIMIT 1", array($user_id));
 
            //判断用户是否存在
            if(!empty($data["id"])) {
 
                //设置图片保存路径
                $path = "image/head/";
                //获取上传文件后返回的文件名和扩展名
                $file_name = $this->uploadPic($user_id, "head", $path);
                //修改用户contact表head头像字段的值
                $conn->executeUpdate("UPDATE contact SET head = ? WHERE id = ?", array($path . $file_name, $user_id));
                $result["flag"] = 1;
                $result["content"] = "上传头像成功!";
            } else {
                $result["flag"] = 3;
                $result["content"] = "用户不存在!";
            }
        }else{
            $result["flag"] = 2;
            $result["content"] = "上传失败,没有选择图片!";
        }
 
        return new Response(json_encode($result), "200", array("Content-Type" => "application/json"));
    }
}
这样图片就上传成功,将用户的id作为文件名,并修改表字段值为图片的全路径

本文来源:http://www.bbyears.com/jiaocheng/79821.html