This article mainly introduces how Symfony2 uses a third-party library Upload to Upload images, and analyzes in detail the steps and skills of Symfony2 using a third-party library Upload Based on the instance form, for more information about how to use the third-party library Upload to Upload images, see the example in this article. We will share this with you for your reference. The details are as follows:
We generally have the Avatar setting function in personal data of applications or websites. In this chapter, we use a third-party Upload library in Symfony2 to create and Upload images.
1. install third-party Libraries
1. Add "require" in the composer. json File
"codeguy/upload": "*"
2. run commands to install
composer update
Ii. Encoding
1. Compile the uploadPic method to upload an image and use the user ID of the uploaded image as the file name.
<? Php/*** @ author Sun * By blogs.zmit.cn http://blogs.zmit.cn * Original works can be reproduced. During reprinting, you must mark the original source of the article in hyperlink form. http://blogs.zmit.cn /6544.html * The author information and this statement of the dream blog. Otherwise, legal liability will be held. */Namespace ZM \ AdminBundle \ Controller; use Symfony \ Bundle \ FrameworkBundle \ Controller; use Symfony \ Component \ Filesystem; class DefaultController extends Controller {public function indexAction ($ name) {return $ this-> render ('zmadminbundle: Default: index.html. twig ', array ('name' => $ name);}/*** upload image ** @ param type $ user_id user id, used as the file name * @ param type $ str name of the file type input in the form * @ Param type $ path: Save path * @ return type */public function uploadPic ($ user_id, $ str, $ path) {$ fs = new Filesystem (); // check whether the path exists if (! $ Fs-> exists ($ path) {// if not, create the directory $ fs-> mkdir ($ path, 0700 );} // use the Upload library $ storage = new \ Upload \ Storage \ FileSystem ($ path); $ file = new \ Upload \ File ($ str, $ storage ); // if the file name is empty, if ($ file-> getName ()! = '') {// Set the file name to the user's id $ file-> setName ($ user_id ); // verify the file Upload $ file-> addValidations (array (// specify the file type new \ Upload \ Validation \ Mimetype (array ('image/png ', 'image/jpg ', 'image/jpeg ', 'image/gif'), // specify the file Size new \ Upload \ Validation \ Size ('2 m '))); // upload the file try {// success $ file-> upload (); // file name and extension $ file_name = $ file-> getNameWithExtension ();} catch (\ Exception $ e) {// failed! $ Errors = $ file-> getErrors () ;}// return the file name and extension return $ file_name ;}}
2. the user uploads the Avatar and saves it to the database table in the full path.
<? Php/*** contact controller * @ author Sun * By blogs.zmit.cn http://blogs.zmit.cn * Original works can be reproduced. During reprinting, you must mark the original source of the article in hyperlink form. http://blogs.zmit.cn /6544.html * The author information and this statement of the dream blog. Otherwise, legal liability will be held. */Namespace ZM \ ApiBundle \ Controller; // reference the Controller of the uploaded image method uploadPic and name it BaseControlleruse ZM \ AdminBundle \ Controller \ defacontroller Controller AS BaseController; use Symfony \ Component \ HttpFoundation \ Request; use Symfony \ Component \ HttpFoundation \ Response; // inherit BaseControllerclass ContactController extends BaseController {/*** upload profile picture ** @ return Response */public function uploadHeadAction () {$ request = Req Uest: createFromGlobals ()-> request; $ user_id = $ request-> get ('user _ id '); // determine whether a file has been uploaded 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); // determines whether the user has if (! Empty ($ data ['id']) {// sets the image storage path $ path = 'image/head /'; // get the file name and extension $ file_name = $ this-> uploadPic ($ user_id, 'head', $ path) returned after the file is uploaded ); // modify the head avatar field of the user contact table $ conn-> executeUpdate ("UPDATE contact SET head =? WHERE id =? ", Array ($ path. $ file_name, $ user_id); $ result ['flag'] = 1; $ result ['content'] = 'the Avatar is uploaded successfully! ';} Else {$ result ['flag'] = 3; $ result ['content'] = 'user does not exist! ';}} Else {$ result ['flag'] = 2; $ result ['content'] =' Upload Failed. No image is selected! ';} Return new Response (json_encode ($ result), '000000', array ('content-type' => 'application/json '));}}
In this way, the image is uploaded successfully, the user id is used as the file name, and the table field value is changed to the full path of the image.
Permanent address: http://blog.it985.com/6544.html
This article is from the IT985 blog. Please indicate the source and relevant links when reprinting.