


php+js iframe realizes uploading avatar interface without jump_PHP tutorial
There are many ways to upload an avatar without redirecting the interface. The one I use is to add an iframe. The code goes directly below.
html:
//route is the backend interface
//upload/avatar is the saving address of the uploaded avatar
//imgurl=/upload/avatar/=$uid?> The last =$uid?> here is for later use of js To realize the real-time display of the latest changed avatar, refer to the code in the js part below
//The avatar is saved as uid.type, such as 1.jpg, 2.png, etc.
//$user[' avatar'] If the user has uploaded an avatar, the avatar field in the user database will be given a timestamp, otherwise it will be empty
php:
$token = param('token');
$user = user_from_token($token);
!$user AND exit(" ");
//File storage path
$file_path="./upload/avatar/";
//664 permission is the file owner Users belonging to the group can read and write, other users can only read.
if(is_dir($file_path) != TRUE) mkdir($file_path, 0664) ;
//Define the file extensions allowed for uploading
$ext_arr = array("gif", "jpg", "jpeg", "png", "bmp");
if (empty($_FILES) === false) {
// Judgment check
$photo_up_size > 2097152 AND exit( " ");
$_FILES["file"]["error"] > 0 AND exit(" ");
//Get 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 (" ");
}
//Delete the same prefix in the directory File
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 with 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 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(" ");
} else {
exit(" ");
}
function ext ($filename) {
return strtolower(substr(strrchr($filename, '.'), 1));
}
/*
Example:
thumb(APP_PATH .'xxx.jpg', APP_PATH.'xxx_thumb.jpg', 200, 200);
Return:
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;
}
// Shrink 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;
}
/*
* 图片裁切
*
* @param string $srcname 原图片路径(绝对路径/*.jpg)
* @param string $forcedheight 裁切后生成新名称(绝对路径/rename.jpg)
* @param int $sourcefile 被裁切图片的X坐标
* @param int $destfile 被裁切图片的Y坐标
* @param int $destext 被裁区域的宽度
* @param int $imgcomp 被裁区域的高度
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;
}
// 先裁切后缩略,因为确定了,width, height, 不需要返回宽高。
function clip_thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80) {
// 获取原图片宽高
$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);
// 原图为横着的矩形
} elseif($src_scale >= $des_scale) {
// 以原图的高度作为标准,进行缩略
$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'];
// 原图为竖着的矩形
} else {
// 以原图的宽度作为标准,进行缩略
$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'];
}
}
?>
我们php中设置返回内容,会发现,在出现相应情况后,返回内容出现在页面的iframe中,所以我们设定了相应的class,以便前端获得返回内容,做出相应处理。clip(),clip_thumb()为裁剪图片函数,可压缩图片大小,裁取图片以左上角为起点,长宽为100的正方形。
js:
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 = $(window.frames['iframe'].document).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());
});
This basically realizes the functions of image upload, upload result prompt, and real-time display of the latest uploaded avatar. There are various plug-ins on the Internet. Although they are rich in functions, they are too large. It depends on our choice.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot
