2019-04-08 16:58:42 3523次浏览 6条回答 0 悬赏 10 金钱
$file->pic = UploadedFile::getInstance($model, 'pic');
$model->pic = $file->upload('users/');

这个一直返回空

表单提交是正常的,ajax提交(不是用的表单)就一直是空的;
UploadedFile::getInstance 这个是只适合表单提交么?

补充于 2019-04-11 11:42

html:

<input type="file" class="avatar_input" name="pic" onchange="handleFiles(this,'icon')" multiple>
<img src="<?=$info['pic']?>" class="avatar" id="icon">

ajax:
function handleFiles(obj,id) {

    file = document.getElementById("icon");
    var files = obj.files;
    img = new Image();
    if(window.URL){
        //File API
        img.src = window.URL.createObjectURL(files[0]); //创建一个object URL,并不是你的本地路径
        img.onload = function(e) {
            window.URL.revokeObjectURL(this.src); //图片加载后,释放object URL
        }
    }

    //上传文件

    var formData = new FormData();
    formData.append('pic', files[0]);
    $.ajax({
        type:"post",
        data:formData,
        cache:false,
        contentType:false,
        processData: false,
        dataType: "json",
        url:"<?=Url::to(['users/up-pic'])?>",
        success:function (data) {
            console.log(data);
            if(data.tag == 1){
                file.src=img.src;
            }else{
                alert(data.msg)
            }
        }
    })
    
    

控制器:
$file = new UploadForm();

        $model = $this->findPicModel(getUserId());
        $opic   =   $model['pic'];

        if (Yii::$app->request->isPost) {
            $file->pic = UploadedFile::getInstance($model, 'pic');
            $model->pic =   $file->upload('users/');

            if ($model->pic) {
                if($model->save()){
                    deletePic($opic);
                    return  Json::encode(['tag'=>1,'msg'=>'ok']);
                }else{
                    deletePic($file->pic);
                    return  Json::encode(['tag'=>0,'msg'=>'保存失败']);
                }
            }else{
                return  Json::encode(['tag'=>0,'msg'=>'获取失败']);
            }
        }else{
            return  Json::encode(['tag'=>0,'msg'=>'非法操作']);
        }
补充于 2019-04-11 15:28

解决了 23333
参数要写 Users[pic] 0。0

  • 回答于 2019-04-08 17:04 举报

    用 ajax 上传文件有点小麻烦。
    以下供参考:

    function test(){
        var form = new FormData(document.getElementById("tf"));
        $.ajax({
            url:"${pageContext.request.contextPath}/public/testupload",
            type:"post",
            data:form,
            processData:false,
            contentType:false,
            success:function(data){
                window.clearInterval(timer);
                console.log("over..");
            },
            error:function(e){
                alert("错误!!");
                window.clearInterval(timer);
            }
        });        
        get();//此处为上传文件的进度条
    }
    
    1 条回复
    回复于 2019-04-08 17:06 回复

    我也是这样写的,控制器是 $_FILES 是能获取图片的,但是 UploadedFile::getInstance这个返回空的,upload 也是空的

  • 回答于 2019-04-09 00:06 举报

    检查一下php环境 打印phpinfo看看是不是不允许上传

    1 条回复
    回复于 2019-04-09 10:11 回复

    不是把。。。我用form表单提交是没问题的, 就ajax 不行,返回的是空

  • 回答于 2019-04-09 17:03 举报

    ajax提交的字段跟rules里一致?

    1 条回复
    回复于 2019-04-11 11:38 回复

    一致啊 都是pic

  • 回答于 2019-04-10 13:15 举报

    你这个名字是不是写错了!或者post提交的csrf的问题

    1 条回复
    回复于 2019-04-11 11:40 回复

    名字没有错把,

  • 回答于 2019-04-14 22:14 举报

    UploadedFile::getInstanceByName('file');
    By Name !!!
    我也被困扰了好久,最终解决了,如果使用了$model->save(); 还要记得
    $this->file->saveAs($this->getFilePath($this->getFileName()), false); 这句里面的false,不然报错,找不到此文件。

    以下是完整代码

    model:

    ['file', 'file', 'skipOnEmpty' => true, 'mimeTypes' => 'image/*, video/*, audio/*, application/zip, application/pdf', 'wrongMimeType' =>'禁止的文件类型',  'tooBig' => '文件太大,仅允许{formattedLimit}']
            ];
    public function upload(){
    		$this->file  = UploadedFile::getInstanceByName('file');
    		if($this->validate()){
    			$this->file->saveAs($this->getFilePath($this->getFileName()), false);
    			return true;
    		}
    		return false;
    	}
        
        controller:
         public function actionCreate() {
    		
    		$model = new Media();
    		if ( isset( $_FILES["file"] ) && !empty( $_FILES["file"]["name"] ) ) {
    			Yii::$app->response->format = 'json';
    			if($model->upload()){
    					$model->src = $model->getSrc();
    					if($model->save()){
    						return ['url' => $model->getUrl($model->getFileName())];
    					}
    			} 
    			return $model->errors; 
    		}  
    		return $this->renderPartial('create', ['model' => $model]);    
        }
        
        JQ: 
         $('html, .upload-area').on('dragenter dragover drop', function (e) { 
    	e.stopPropagation();  
    	e.preventDefault(); 
    	$('.upload-message').text('拖放到这里');
    });
    
     $('.modal').on('click','.upload-area',function(){
    	$('#file').click();
    });
    
    $('.modal').on('drop', '.upload-area',function (e) {
        e.stopPropagation();
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        var formData = new FormData();
    
    	$.each(files, function(i, file) {
    		formData.append('file', files[i]);
    		uploadData(formData);
    	});  
    });
    
    $('.modal').on('change','#file',function(){
    	var formData = new FormData();
    	$.each($('#file')[0].files, function(i, file) {
    		formData.append('file', $('#file')[0].files[i]);
    		uploadData(formData);
    	});
    });
    
    function uploadData(formData){
        $.ajax({
            url: '/media/create',
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
    		beforeSend:function(){ $('.upload-message').text("上传中...");},
            success: function(response){
    			if(response.url){
    				$('.upload-message').html(response.url);
    				$.pjax.reload({container: '#pjax'});
    			}else{
    				$('.upload-message').html(response.file);
    			} 
            }
        });
    }
    
    
    HTML:
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <b class="upload-title">上传文件</b>
    </div>
    <div class="modal-body upload-file">
    <input type="file" name="file" id="file" multiple>
    <div class="upload-area">
    <div class="upload-message">拖文件到这儿<br/><br/>点击选择 </div>	
    </div>
    </div>
    
  • 回答于 2019-11-23 21:34 举报

    请问楼主,您说的参数要写 Users[pic] 0。0是写在哪里?怎么写

您需要登录后才可以回答。登录 | 立即注册
筱筱溺水寒
助理

筱筱溺水寒

注册时间:2017-02-15
最后登录:2019-04-18
在线时长:4小时43分
  • 粉丝2
  • 金钱145
  • 威望0
  • 积分185

热门问题