This article mainly introduces the php + js Upload Avatar interface without redirection. iframe is used in this example. if you need it, refer to iFrame.
There are many ways to upload an avatar without navigation on the interface. I use an iframe. The following code is used directly.
Html:
The code is as follows:
// Route is the backend interface
// Upload/avatar is the address for storing the uploaded avatar
// Imgurl =/upload/avatar/ The last It is used to instantly display the latest replaced Avatar with js later. refer to the following JavaScript code.
// The header is named uid.type, such as 1.jpg and 2.png.
// $ User ['Avatar '] If a user has uploaded an avatar, the avatar field in the user database will be assigned a timestamp; otherwise, it will be blank.
Php:
The code is as follows:
$ Token = param ('token ');
$ User = user_from_token ($ token );
! $ User AND exit ("
$ Lang [user_not_exists]
");
// File storage path
$ File_path = "./upload/avatar /";
// 664 read and write permissions are granted to the file owner and owner group users, while others are read-only.
If (is_dir ($ file_path )! = TRUE) mkdir ($ file_path, 0664 );
// Define the file extension that can be uploaded
$ Ext_arr = array ("gif", "jpg", "jpeg", "png", "bmp ");
If (empty ($ _ FILES) === false ){
// Judgment check
$ Photo_up_size> 2097152 AND exit ("
Sorry, the photo you uploaded exceeds 2 MB
");
$ _ FILES ["file"] ["error"]> 0 AND exit ("
File upload error: ". $ _ FILES [" file "] [" error "]."
");
// Obtain the file extension
$ Temp_arr = explode (".", $ _ FILES ["file"] ["name"]);
$ File_ext = array_pop ($ temp_arr );
$ File_ext = trim ($ file_ext );
$ File_ext = strtolower ($ file_ext );
// Check the extension
If (in_array ($ file_ext, $ ext_arr) === false ){
Exit ("
The file Upload extension is not allowed.
");
}
// Delete objects with the same prefix in the directory
If ($ dh = opendir ($ file_path )){
While ($ file = readdir ($ dh ))! = False ){
$ File_arr = $ file. split ('.');
If ($ file_arr [0] = $ user ['uid']) unlink ($ file_path. $ file );
}
}
// Rename the file as uid
$ New_name = $ user ['uid']. ".". $ file_ext;
// Move the file to the storage directory
Move_uploaded_file ($ _ FILES ["file"] ["tmp_name"], $ file_path. $ new_name );
// Crop the compressed image
Clip ($ file_path. $ new_name, $ file_path. $ new_name, 0, 0,100,100 );
Clip_thumb ($ file_path. $ new_name, $ file_path. $ new_name, 100,100 );
// Write file storage information to the data table for management
User_update ($ user ['uid'], array ('Avatar '=> time ()));
Exit ("
File uploaded
");
} Else {
Exit ("
Incorrect file Upload
");
}
Function ext ($ filename ){
Return strtolower (substr (strrchr ($ filename, '.'), 1 ));
}
/*
Instance:
Thumb(APP_PATH.'xxx.jpg ', APP_PATH.'xxx_thumb.jpg', 200,200 );
Return value:
Array ('filesize' => 0, 'width' => 0, 'height' => 0)
*/
Function thumb ($ sourcefile, $ destfile, $ forcedwidth = 80, $ forcedheight = 80 ){
$ Return = array ('filesize' => 0, 'width' => 0, 'height' => 0 );
$ Imgcomp = 10;
$ Destext = ext ($ destfile );
If (! In_array ($ destext, array ('GIF', 'jpg ', 'bmp', 'PNG '))){
Return $ return;
}
$ Imgcomp = 100-$ imgcomp;
$ Imginfo = getimagesize ($ sourcefile );
$ Src_width = $ imginfo [0];
$ Src_height = $ imginfo [1];
If ($ src_width = 0 | $ src_height = 0 ){
Return $ return;
}
$ Src_scale = $ src_width/$ src_height;
$ Des_scale = $ forcedwidth/$ forcedheight;
If (! Function_exists ('imagecreatefromjpeg ')){
Copy ($ sourcefile, $ destfile );
$ Return = array ('filesize' => filesize ($ destfile), 'width' => $ src_width, 'height' => $ src_height );
Return $ return;
}
// Scale down according to the specified proportion
If ($ src_width <= $ forcedwidth & $ src_height <= $ forcedheight ){
$ Des_width = $ src_width;
$ Des_height = $ src_height;
} Elseif ($ src_scale> = $ des_scale ){
$ Des_width = ($ src_width >=$ forcedwidth )? $ Forcedwidth: $ src_width;
$ Des_height = $ des_width/$ src_scale;
$ Des_height = ($ des_height >=$ forcedheight )? $ Forcedheight: $ des_height;
} Else {
$ Des_height = ($ src_height >=$ forcedheight )? $ Forcedheight: $ src_height;
$ Des_width = $ des_height * $ src_scale;
$ Des_width = ($ des_width >=$ forcedwidth )? $ Forcedwidth: $ des_width;
}
Switch ($ imginfo ['Mime ']) {
Case 'image/jpeg ':
$ Img_src = imagecreatefromjpeg ($ sourcefile );
! $ Img_src & $ img_src = imagecreatefromgif ($ sourcefile );
Break;
Case 'image/GIF ':
$ Img_src = imagecreatefromgif ($ sourcefile );
! $ Img_src & $ img_src = imagecreatefromjpeg ($ sourcefile );
Break;
Case 'image/png ':
$ Img_src = imagecreatefrompng ($ sourcefile );
Break;
Case 'image/wbmp ':
$ Img_src = imagecreatefromwbmp ($ sourcefile );
Break;
Default:
Return $ return;
}
$ Img_dst = imagecreatetruecolor ($ des_width, $ des_height );
$ Img_color = imagecolorallocate ($ img_dst, 255,255,255 );
Imagefill ($ img_dst, 0, 0, $ img_color );
Imagecopyresampled ($ img_dst, $ img_src, 0, 0, 0, 0, $ des_width, $ des_height, $ src_width, $ src_height );
// $ Tmpfile = $ temp_path.md5 ($ destfile );
$ Tmpfile = $ destfile;
Switch ($ destext ){
Case 'jpg ': imagejpeg ($ img_dst, $ tmpfile, $ imgcomp); break;
Case 'GIF': imagegif ($ img_dst, $ tmpfile, $ imgcomp); break;
Case 'PNG ': imagepng ($ img_dst, $ tmpfile, version_compare (PHP_VERSION, '5. 1.2') = 1? 7: 70); break;
}
$ R = array ('filesize' => filesize ($ tmpfile), 'width' => $ des_width, 'height' => $ des_height );;
Copy ($ tmpfile, $ destfile );
// Unlink ($ tmpfile );
Imagedestroy ($ img_dst );
Return $ r;
}
/*
* Cropping images
*
* @ Param string $ original image path of srcname (absolute path/*. jpg)
* @ Param string $ forcedheight crop and generate a new name (absolute path/rename.jpg)
* @ Param int $ X coordinate of the cropped image in sourcefile
* @ Param int $ Y coordinate of the cropped image in destfile
* @ Param int $ destext width of the cut area
* @ Param int $ height of the imgcomp cut area
Clip ('XXX/x.jpg ', 'xXx/newx.jpg', 10, 40,150,150)
*/
Function clip ($ sourcefile, $ destfile, $ clipx, $ clipy, $ clipwidth, $ clipheight ){
$ Getimgsize = getimagesize ($ sourcefile );
If (empty ($ getimgsize )){
Return 0;
} Else {
$ Imgwidth = $ getimgsize [0];
$ Imgheight = $ getimgsize [1];
If ($ imgwidth = 0 | $ imgheight = 0 ){
Return 0;
}
}
If (! Function_exists ('imagecreatefromjpeg ')){
Copy ($ sourcefile, $ destfile );
Return filesize ($ destfile );
}
Switch ($ getimgsize [2]) {
Case 1:
$ Imgcolor = imagecreatefromgif ($ sourcefile );
Break;
Case 2:
$ Imgcolor = imagecreatefromjpeg ($ sourcefile );
Break;
Case 3:
$ Imgcolor = imagecreatefrompng ($ sourcefile );
Break;
}
// $ Imgcolor = imagecreatefromjpeg ($ sourcefile );
$ Img_dst = imagecreatetruecolor ($ clipwidth, $ clipheight );
$ Img_color = imagecolorallocate ($ img_dst, 255,255,255 );
Imagefill ($ img_dst, 0, 0, $ img_color );
Imagecopyresampled ($ img_dst, $ imgcolor, 0, 0, $ clipx, $ clipy, $ imgwidth, $ imgheight, $ imgwidth, $ imgheight );
$ Tmpfile = $ destfile;
Imagejpeg ($ img_dst, $ tmpfile, 100 );
$ N = filesize ($ tmpfile );
Copy ($ tmpfile, $ destfile );
Return $ n;
}
// Crop the image first and then scale it down, because the width and height parameters are fixed. you do not need to return the width and height values.
Function clip_thumb ($ sourcefile, $ destfile, $ forcedwidth = 80, $ forcedheight = 80 ){
// Obtain the width and height of the original image
$ Getimgsize = getimagesize ($ sourcefile );
If (empty ($ getimgsize )){
Return 0;
} Else {
$ Src_width = $ getimgsize [0];
$ Src_height = $ getimgsize [1];
If ($ src_width = 0 | $ src_height = 0 ){
Return 0;
}
}
$ Src_scale = $ src_width/$ src_height;
$ Des_scale = $ forcedwidth/$ forcedheight;
If ($ src_width <= $ forcedwidth & $ src_height <= $ forcedheight ){
$ Des_width = $ src_width;
$ Des_height = $ src_height;
$ N = clip ($ sourcefile, $ destfile, 0, 0, $ des_width, $ des_height );
Return filesize ($ destfile );
// The original image is a horizontal rectangle.
} Elseif ($ src_scale> = $ des_scale ){
// Scale down the source image based on its height
$ Des_height = $ src_height;
$ Des_width = $ src_height/$ des_scale;
$ N = clip ($ sourcefile, $ destfile, 0, 0, $ des_width, $ des_height );
If ($ n <= 0) return 0;
$ R = thumb ($ destfile, $ destfile, $ forcedwidth, $ forcedheight );
Return $ r ['filesize'];
// The original image is a vertical rectangle.
} Else {
// Scale down the source image based on its width
$ Des_width = $ src_width;
$ Des_height = $ src_width/$ des_scale;
$ N = clip ($ sourcefile, $ destfile, 0, 0, $ des_width, $ des_height );
If ($ n <= 0) return 0;
$ R = thumb ($ destfile, $ destfile, $ forcedwidth, $ forcedheight );
Return $ r ['filesize'];
}
}
?>
When we set the returned content in php, we will find that the returned content appears in the iframe of the page after the corresponding situation, so we set the corresponding class so that the front end can get the returned content, make corresponding processing. Clip (), clip_thumb () is the cropping image function, which can compress the image size. the cropped image starts from the upper left corner and has a square with a length of 100.
Js:
The code is as follows:
Var jsubmit_file = jinput. filter ('[name = "submit_file"]');
Var jfile = jinput. filter ('[name = "file"]');
Var jiframe = $ ('# iframe ');
Var jthumb = $ ('. thumb ');
Var type = '';
Jfile. on ('change', function (){
Var path = jfile. val ();
Var file_arr = path. split ('.');
Type = file_arr [file_arr.length-1];
Jsubmit_file.trigger ('click ');
});
Jiframe. on ('load', function (){
Var jiframe_message = messages ({{frames}'iframe'}.doc ument). find ('. iframe_message ');
If (jiframe_message.attr ('status ')! = 0 ){
Var url = this. contentWindow. location. href;
Var url_arr = url. split ('= ');
Jthumb. attr ('src', url_arr [1] + '.' + type );
}
Alert (jiframe_message.text ());
});
In this way, the functions of image upload, upload result prompt, and instant display of the latest uploaded avatar are basically realized. There are various plug-ins on the Internet, although the functions are rich, that is, the size is too large, we chose this.