$instance
$instance : object
Reference to the CI singleton
上传
This class object is the super class that every library in CodeIgniter will be assigned to.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* 上传
* */
class Upload extends CI_Controller
{
private static $data = array();
public function __construct()
{
parent::__construct();
define('ALLOW_UPLOAD_IMAGE_TYPES', 'jpg, jpeg, png, gif'); // 允许上传的图片类型
define('MAX_UPLOAD_SIZE', 2097152); // 最大允许上传的图片大小(1M = 1024 * 1024 = 1048576)
// ===========================头像裁切尺寸
define('AVATAR_WIDTH', 160);
define('AVATAR_HEIGHT', 160);
// ===========================最大图片尺寸,过大时将自动按比例缩小,防止超大图片撑破页面
define('AVATAR_MAX_WIDTH', 500);
define('AVATAR_MAX_HEIGHT', 500);
}
//华为对象存储上传
public function hwupload($fileKey='file'){
$this->load->library('obs_upload/obs_upload');
$dir='attachment/'.date('Ym').'/'.date('d').'/';
$res=$this->obs_upload->do_upload($dir,$fileKey); //第二个参数为上传文件的name
$out=[];
if ($res['code']==200){
$out['errno']=0;
foreach ($res['content'] as $key=>$val){
$out['data'][$key]=$this->config->item('hwclouds').$val['url'];
}
}
//var_dump($res);die();
echo json_encode($out);
}
public function uploadImage( $imagePath='imagePath' )
{
$this->load->library('Bd_upload');
if (!empty($_FILES[$imagePath]['tmp_name']))
{
$allowpictype = array('jpg','jpeg','gif','png');
$image_path_array = $this->bd_upload->file_save( $_FILES[$imagePath] ,$allowpictype ,FALSE ,0 ,0 );
echo json_encode($image_path_array);
exit();
}
}
/*
* 用户头像
* */
public function useravatar()
{
$this->load->view('admincp/common/useravatar', self::$data);
}
/**
* ajax 处理用户头像
* */
public function ajaxuploadavatar()
{
//$this->load->library('Uploader',explode(', ', ALLOW_UPLOAD_IMAGE_TYPES), MAX_UPLOAD_SIZE);
$imgtype = explode(', ', ALLOW_UPLOAD_IMAGE_TYPES);
$this->load->library('Uploader',array('imgtype'=>$imgtype,'maxsize'=>MAX_UPLOAD_SIZE));
//include('models'.DIRECTORY_SEPARATOR.'uploader.php');
//$uploader = new uploader( explode(', ', ALLOW_UPLOAD_IMAGE_TYPES), MAX_UPLOAD_SIZE );
//var_dump($this->uploader);exit;
$result = $this->uploader->upload( 'uploadtmp'.DIRECTORY_SEPARATOR ); // 先保存到临时文件夹
$reponse = new stdClass();
if( isset($result['success']) && $result['success'] )
{
//include('models'.DIRECTORY_SEPARATOR.'gd.php');
$this->load->library('Gd');
$src_path = 'uploadtmp'.DIRECTORY_SEPARATOR.$this->uploader->get_real_name();
$this->gd->open( $src_path );
if( $this->gd->is_image() )
{
if( $this->gd->get_width() < AVATAR_WIDTH )
{
$reponse->success = false; // 传递给 file-uploader 表示服务器端已处理
$reponse->description = '您上传的图片宽度('.$this->gd->get_width().'像素)过小!最小需要'.AVATAR_WIDTH.'像素。';
}
else if( $this->gd->get_height() < AVATAR_HEIGHT )
{
$reponse->success = false; // 传递给 file-uploader 表示服务器端已处理
$reponse->description = '您上传的图片高度('.$this->gd->get_height().'像素)过小!最小需要'.AVATAR_HEIGHT.'像素。';
}
else
{
$reponse->success = true;
$reponse->tmp_avatar = $this->uploader->get_real_name();
if($this->gd->get_width()>AVATAR_MAX_WIDTH || $this->gd->get_height() > AVATAR_MAX_HEIGHT)
{
// 图片过大时按比例缩小,防止超大图片撑破页面
$this->gd->resize_to(AVATAR_MAX_WIDTH, AVATAR_MAX_HEIGHT, 'scale');
$this->gd->save_to( $src_path );
}
}
}
}
else if( isset($result['error']) )
{
$reponse->success = false;
$reponse->description = $result['error'];
}
header('Content-type: application/json');
echo json_encode($reponse);
}
private function get_server_ip()
{
if (isset($_SERVER)) {
if($_SERVER['SERVER_ADDR']) {
$server_ip = $_SERVER['SERVER_ADDR'];
} else {
$server_ip = $_SERVER['LOCAL_ADDR'];
}
} else {
$server_ip = getenv('SERVER_ADDR');
}
return $server_ip;
}
/**
* ajax 裁切头像图片
* */
public function ajaxcrop()
{
$tmp_avatar = $_POST['tmp_avatar'];
$x1 = $_POST['x1'];
$y1 = $_POST['y1'];
$x2 = $_POST['x2'];
$y2 = $_POST['y2'];
$w = $_POST['w'];
$h = $_POST['h'];
$reponse = new stdClass();
$src_path = 'uploadtmp'.DIRECTORY_SEPARATOR.$tmp_avatar;
if(!file_exists($src_path))
{
$reponse->success = false;
$reponse->description = '未找到图片文件';
}
else
{
$this->load->library('Gd');
$this->gd->open( $src_path );
if( $this->gd->is_image() )
{
$this->gd->crop($x1, $y1, $w, $h);
$this->gd->resize_to(AVATAR_WIDTH, AVATAR_HEIGHT, 'scale_fill');
$avatar_name = 'a'.date('His').'_'.md5(uniqid()).'.'.$this->gd->get_type();
$this->gd->save_to('uploadtmp'.DIRECTORY_SEPARATOR.$avatar_name);
//上传到图片服务器
$mainfile = $fdfsthum = array();
$this->load->library('Fastdfsclient');//fastdfs操作类
$src_path = realpath($src_path);
$avatars_path = 'uploadtmp'.DIRECTORY_SEPARATOR.$avatar_name;
$avatars_path = realpath($avatars_path);;
if(!empty($src_path) && !empty($avatars_path))
{
$mainfile = $this->fastdfsclient->fdfs_upload($src_path);
if(!empty($mainfile))
{
$fdfsthum = $this->fastdfsclient->fdfs_upload_slave($avatars_path ,$mainfile['group_name'],$mainfile['sourcefile'],'_avatars');
if(!$fdfsthum)
{
$fdfsthum = $this->fastdfsclient->fdfs_upload_slave($avatars_path ,$mainfile['group_name'],$mainfile['sourcefile'],'_avatars');
}
}
}
if(!empty($mainfile['filename']) && !empty($fdfsthum['filename']))
{
$reponse->success = true;
$reponse->avatar = $fdfsthum['filename'];
$reponse->originalavatar = $mainfile['filename'];
$reponse->description = '';
}
else
{
$reponse->success = false;
$reponse->description = '上传失败';
}
@unlink($src_path);
@unlink($avatars_path);
}
else
{
$reponse->success = false;
$reponse->description = '该图片文件不是有效的图片';
}
}
header('Content-type: application/json');
echo json_encode($reponse);
}
public function deltmpimg()
{
$imgurl = $this->input->post('tmpimgsrc');
if(!empty($imgurl))
{
$src_path = 'uploadtmp'.DIRECTORY_SEPARATOR.$imgurl;
@unlink($src_path);
}
echo 0;
}
public function fileupload()
{
$imgUrl = $this->config->item('img_url').'/';
$this->load->model('Upload_model','upload');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit;
}
if ( !empty($_REQUEST[ 'debug' ]) ) {
$random = rand(0, intval($_REQUEST[ 'debug' ]) );
if ( $random === 0 ) {
header("HTTP/1.0 500 Internal Server Error");
exit;
}
}
@set_time_limit(5 * 60);
$targetDir = 'uploadtmp/upload_tmp';
$uploadDir = 'uploadtmp/upload';
$cleanupTargetDir = true;
$maxFileAge = 5 * 3600;
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
// Create target dir
if (!file_exists($uploadDir)) {
@mkdir($uploadDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir.'/'.$fileName;
$uploadPath = $uploadDir.'/'.date('YmdHis').'-'.md5(uniqid()).rand(1,9999).$fileName;
//var_dump($uploadPath);
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir.'/'.$file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (!$in = @fopen("php://input", "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
$index = 0;
$done = true;
for( $index = 0; $index < $chunks; $index++ ) {
if ( !file_exists("{$filePath}_{$index}.part") ) {
$done = false;
break;
}
}
if ( $done ) {
if (!$out = @fopen($uploadPath, "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if ( flock($out, LOCK_EX) ) {
for( $index = 0; $index < $chunks; $index++ ) {
if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
break;
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($in);
@unlink("{$filePath}_{$index}.part");
}
flock($out, LOCK_UN);
}
@fclose($out);
}
$thumbconfig = $this->config->item('imgSize');
$upfile = $this->upload->uploadImage('', $uploadPath, $thumbconfig);
if(!empty($upfile['data']['original']['filename']))
{
$data = array(
'original' => $imgUrl.$upfile['data']['original']['filename'], 'originalurl' => $upfile['data']['original']['filename'], 'smallimg'=>$imgUrl.$upfile['data']['small']['filename']
);
die('{"jsonrpc" : "2.0", "result" : '.json_encode($data).', "id" : "id"}');
}
else
{
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
//var_dump($upfile);
// Return Success JSON-RPC response
}
public function preview()
{
$DIR = 'uploadtmp/preview';
// Create target dir
if (!file_exists($DIR)) {
@mkdir($DIR);
}
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
if ($cleanupTargetDir)
{
if (!is_dir($DIR) || !$dir = opendir($DIR))
{
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false)
{
$tmpfilePath = $DIR . DIRECTORY_SEPARATOR . $file;
// Remove temp file if it is older than the max age and is not the current file
if (@filemtime($tmpfilePath) < time() - $maxFileAge)
{
@unlink($tmpfilePath);
}
}
closedir($dir);
}
$src = file_get_contents('php://input');
//var_dump($src);
if (preg_match("#^data:image/(\w+);base64,(.*)$#", $src, $matches))
{
$previewUrl = $this->config->item('base_url').'/';
$base64 = $matches[2];
//var_dump($base64);
$type = $matches[1];
if ($type === 'jpeg') {
$type = 'jpg';
}
$filename = md5($base64).".$type";
$filePath = $DIR.DIRECTORY_SEPARATOR.$filename;
if (file_exists($filePath))
{
die('{"jsonrpc" : "2.0", "result" : "'.$previewUrl.'uploadtmp/preview/'.$filename.'", "id" : "'.md5($base64).'"}');
}
else
{
$data = base64_decode($base64);
file_put_contents($filePath, $data);
die('{"jsonrpc" : "2.0", "result" : "'.$previewUrl.'uploadtmp/preview/'.$filename.'", "id" : "'.md5($base64).'"}');
}
} else {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "un recoginized source"}}');
}
}
/**
* 图片上传
* */
public function uploadimg()
{
$this->load->model('Upload_model','upload');
$thumbconfig = $this->config->item('imgSize');
$fileName = $this->input->get_post('file');
$fileName = empty($fileName)?'photoimg':$fileName;
echo $fileName;exit;
$upfile = $this->upload->uploadImage('photoimg', $thumbconfig);
var_dump($upfile);return false;
$previewUrl = $this->config->item('img_url').'/';
if(!empty($upfile['data']['original']['filename']))
{
$data = array(
'err'=>0,
'originalimg'=>$previewUrl.$upfile['data']['original']['filename'],
'bigimg'=>$previewUrl.$upfile['data']['big']['filename'],
'smallimg'=>$previewUrl.$upfile['data']['small']['filename'],
'original'=>$upfile['data']['original']['filename']
);
echo json_encode($data);exit;
}
else
{
echo json_encode($upfile);exit;
}
}
/**
* 图片上传
* */
public function uploadimg1()
{
var_dump($_FILES);exit;
$this->load->model('Upload_model','upload');
$thumbconfig = $this->config->item('imgSize');
$fileName = $this->input->get_post('file');
$fileName = empty($fileName)?'photoimg':$fileName;
echo $fileName;exit;
$upfile = $this->upload->uploadImage('photoimg', $thumbconfig);
var_dump($upfile);return false;
$previewUrl = $this->config->item('img_url').'/';
if(!empty($upfile['data']['original']['filename']))
{
$data = array(
'err'=>0,
'originalimg'=>$previewUrl.$upfile['data']['original']['filename'],
'bigimg'=>$previewUrl.$upfile['data']['big']['filename'],
'smallimg'=>$previewUrl.$upfile['data']['small']['filename'],
'original'=>$upfile['data']['original']['filename']
);
echo json_encode($data);exit;
}
else
{
echo json_encode($upfile);exit;
}
}
/**
* 上传头像
* */
public function uploadavatar()
{
$this->load->model('Upload_model','upload');
$avatarsconfig = $this->config->item('avatarsSize');
$upfile = $this->upload->uploadImage('avatarsimg', '', $avatarsconfig);
$previewUrl = $this->config->item('img_url').'/';
if(!empty($upfile['data']['original']['filename']))
{
$data = array(
'err'=>0,
'originalimg'=>$previewUrl.$upfile['data']['original']['filename'],
'avatarsimg'=>$previewUrl.$upfile['data']['avatars']['filename'],
'original'=>$upfile['data']['original']['filename']
);
echo json_encode($data);exit;
}
else
{
echo json_encode(array('err'=>1));exit;
}
}
/**
* 上传附件lxn 3-17
* */
public function uploadFile()
{
$this->load->model('Upload_model','upload');
$thumbconfig = $this->config->item('imgSize');
$upfile = $this->upload->uploadfile('photoimg', '', $thumbconfig);
$previewUrl = $this->config->item('img_url').'/';
if(!empty($upfile['data']['original']['filename']))
{
$data = array(
'err'=>0,
'originalimg'=>$previewUrl.$upfile['data']['original']['filename'],
'bigimg'=>$previewUrl.$upfile['data']['big']['filename'],
'smallimg'=>$previewUrl.$upfile['data']['small']['filename'],
'original'=>$upfile['data']['original']['filename']
);
echo json_encode($data);exit;
}
else
{
echo json_encode($upfile);exit;
}
}
//华为对象存储文件上传方法
public function index($name='file'){
// echo 11;exit;
// var_dump($_FILES);exit;
// exit;
$this->load->library('obs_upload/obs_upload');
$dir='attachment/'.date('Ym').'/'.date('d').'/';
$res=$this->obs_upload->do_upload($dir,$name); //第二个参数为上传文件的
//var_dump($res);
ob_end_clean();
echo json_encode($res);
}
}