目标:1.部署前端插件uploadify
2.编写image.js
3.编写图片上传API接口实现图片完美异步上传
预先配置:
config.php:
<?php
//配置文件
return [
'default_return_type' => 'json',
];
这样子api的输出都是json形式来输出的
插件处理:
将下载好的插件解压到,
入口文件的后台模块,插件内容,
对里面的部分文件做下修改:
uploadify.css 中的
.uploadify-queue-item .cancel a {
background: url('./uploadify-cancel.png') 0 0 no-repeat;
float: right;
height: 16px;
text-indent: -9999px;
width: 16px;
}
修改为:
background: url('./uploadify-cancel.png') 0 0 no-repeat;
插件的引入:
在对应的模块:
footer.html引入js:
{load href="__STATIC__/admin/uploadify/jquery.uploadify.min.js" /}
{load href="__STATIC__/admin/js/image.js" /}
然后在
建立image.js
将http://www.uploadify.com/documentation/uploadify/onuploadsuccess/页面的
$(function() {
$("#file_upload").uploadify({
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'onUploadSuccess' : function(file, data, response) {
alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
}
});
});
由于这里面的地址是写死的,为了方便代码的复用性,做些更改
找到对应模块的view层,找到对应的页面,定义
var SCOPE = {
'uploadify_swf' :'__STATIC__/admin/uploadify/uploadify.swf',
'image_upload' :'{:url('api/image/upload')}',
};
然后在image.js修改为:
'swf' : SCOPE.uploadify_swf,
'uploader' : SCOPE.image_upload,
继续完善image.js:
$(function() {
$("#file_upload").uploadify({
'swf' : SCOPE.uploadify_swf,
'uploader' : SCOPE.image_upload,
'buttonText' : '图片上传',
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png',
'fileObjName' : 'file',
'onUploadSuccess' : function(file, data, response) {
}
});
编写api接口image.php
<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use think\File;
class Image extends Controller
{
public function upload(){
$file = Request::instance()->file('file');
//给定一个目录
$info = $file->move('upload');
if ($info && $info->getPathname()){
return show(1,'success','/'.$info->getPathname());
}
return show(0,'upload error');
}
}
upload为图片上传目录,会在入口文件目录自动生成,图片上传后有个回调的接口images中的onUploadSuccess,为了使图片能够显示,继续完善image.js
$(function() {
$("#file_upload").uploadify({
'swf' : SCOPE.uploadify_swf,
'uploader' : SCOPE.image_upload,
'buttonText' : '图片上传',
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png',
'fileObjName' : 'file',
'onUploadSuccess' : function(file, data, response) {
//console.log(file);
//console.log(data); {"status":1,"message":"success","data":"\/upload\\20170611\\1c365af70093b2ecab7ccca9e645b300.jpg"}
//console.log(response); true
if(response){
var obj =JSON.parse(data);
$("#upload_org_code_img").attr("src",obj.data);
$("#file_upload_image").attr("value",obj.data);
$("#upload_org_code_img").show();
}
}
});
});
其中
$("#upload_org_code_img").attr("src",obj.data);
$("#upload_org_code_img").show();
这个是为了图片能够正常显示出来
$("#file_upload_image").attr("value",obj.data);
这个是表单提交的时候获取图片
如果页面有其他地方也需要可以修改里面的$("#file_upload")去对应id就可以了