ajax 上传文件 UploadedFile::getInstance 返回空 [ 2.0 版本 ]
$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
共 6 个回答
-
用 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 条回复 -
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>
筱筱溺水寒
注册时间:2017-02-15
最后登录:2019-04-18
在线时长:4小时43分
最后登录:2019-04-18
在线时长:4小时43分
- 粉丝2
- 金钱145
- 威望0
- 积分185