yii2 文件异步上传 [ 技术分享 ]
- composer "kartik-v/yii2-widget-fileinput": "@dev",
2.activeform
<?= $form->field($uploadForm , 'imageFile')->widget(FileInput::className(),[
'options' => [
],
'pluginOptions' => [
'browseLabel'=>'提交图片',
'layoutTemplates'=>[
'progress' => '',
],
'showCancel'=>false,
'showCaption'=>false,
// 需要预览的文件格式
'showRemove'=>false,
'showUpload'=>false,
'showPreview' => false,
// 是否展示预览图
'initialPreviewAsData' => false,
'uploadUrl' => Url::to(['category/uploads']),
'uploadExtraData' => [
'model' => 'rotatain' //这个参数可以省略,额外的POST数据,我这里用来保存图片的属性到数据库中方便管理图片资源rotatain为Rotatain AR模型
],
],
//网上很多地方都没详细说明回调触发事件,其实fileupload为上传成功后触发的,三个参数,主要是第二个,有formData,jqXHR以及response参数,上传成功后返回的ajax数据可以在response获取
'pluginEvents' => [
'fileselect' =>"function(event, numFiles, label) {
// alert('data');
jQuery('#uploadform-imagefile').fileinput('upload');
}",
'fileuploaded' => "function (object,data){
//
//console.log(1)
//alert(data.response.imageUrl);
ajaxCallback(data);
//document.getElementsByClassName('kv-upload-progress').style.display='none';
//$('.field-rotatain-image').show().find('input').val(data.response.imageUrl);
}",
//错误的冗余机制
'error' => "function (){
alert('图片上传失败');
}"
]
]);
?>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
//单图上传 function ajaxCallback(data){
var str = '<img style="width:100px;height:100px;margin-right:10px;" src='+data.response.imageUrl +'>'
//$("#imgdiv").append(str);
document.getElementById("imgdiv").innerHTML=str;
}
//多图上传 //多图数组 var imgArray=[] function ajaxCallbackMultiple(data){
}
2.controller
public function actionUploads()
{
$post =Yii::$app->request->isPost;
$uploadForm->imageFile = UploadedFile::getInstance($uploadForm, 'imageFile');
if($imageUrl = $uploadForm->upload()){
echo Json::encode([
'imageUrl' => $imageUrl,
'error' => '' //上传的error字段,如果没有错误就返回空字符串,否则返回错误信息,客户端会自动判定该字段来认定是否有错
]);exit;
}else{
echo Json::encode([
'imageUrl' => '',
'error' => '文件上传失败'
]);exit;
}
}
3.model
<?php namespace app\models;
use yii\base\Model; use yii\web\UploadedFile;
class UploadForm extends Model {
/**
* @var UploadedFile
*/
public $imageFile; public $imageUrl; public $imageFiles;
public function rules()
{
return [
//数据验证这里可自己做
//[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function attributeLabels()
{
return [
'imageFile' => '封面图',
'imageFiles'=>'详情图',
];
}
public function upload()
{
if($this->validate()){
$path = "../ss/basic/uploads". '/' . date("Ymd");
if(!is_dir($path) || !is_writable($path)){
\yii\helpers\FileHelper::createDirectory($path,0777,true);
}
$filePath = $path . '/' . \Yii::$app->request->post('uploadForm','') . '_' .md5(uniqid() . mt_rand(10000,99999999)) . '.' . $this->imageFile->extension;
if( $this->imageFile->saveAs($filePath)){
//这里将上传成功后的图片信息保存到数据库
$imageUrl = $this->parseImageUrl($filePath);
/// echo $imageUrl;exit;
// $imageModel = new Images();
// $imageModel->url = $imageUrl;
// $imageModel->addtime = time();
// $imageModel->status = 0;
// $imageModel->module = \Yii::$app->request->post('model','');
// $imageModel->save(false);
return $imageUrl;
}
}
return false;
}
public function uploads()
{
if($this->validate()){
$path = "../ss/basic/uploads". '/' . date("Ymd");
if(!is_dir($path) || !is_writable($path)){
\yii\helpers\FileHelper::createDirectory($path,0777,true);
}
$filePath = $path . '/' . \Yii::$app->request->post('uploadForm','') . '_' .md5(uniqid() . mt_rand(10000,99999999)) . '.' . $this->imageFiles->extension;
if( $this->imageFiles->saveAs($filePath)){
//这里将上传成功后的图片信息保存到数据库
$imageUrl = $this->parseImageUrl($filePath);
/// echo $imageUrl;exit;
// $imageModel = new Images();
// $imageModel->url = $imageUrl;
// $imageModel->addtime = time();
// $imageModel->status = 0;
// $imageModel->module = \Yii::$app->request->post('model','');
// $imageModel->save(false);
return $imageUrl;
}
}
return false;
}
/**
* 这里在upload中定义了上传目录根目录别名,以及图片域名
* 将/var/www/html/gushanxia/upload/20160626/file.png 转化为 http://statics.gushanxia.com/20160626/file.png
* format:http://domain/path/file.extension
* @param $filePath
* @return string
*/
private function parseImageUrl($filePath)
{
return $filePath;
}
}
共 0 条回复
没有找到数据。
496736806
注册时间:2017-07-13
最后登录:2018-12-07
在线时长:2小时27分
最后登录:2018-12-07
在线时长:2小时27分
- 粉丝1
- 金钱55
- 威望10
- 积分175