在某种特殊情况下我们上传图片不能用form表单,那么只能用ajax对单个图片进行上传或修改,利用formdata就能很好的实现,下面上代码,js中的只是关于formdata如何获取图片资源的一部分代码,剩余的ajax上传就按正常写法来写就可以
js:
var formdata = new FormData();
formdata.append('img', $("#imgFile"+o)[0].files[0]);
formdata.append('option_id', $("#option_id"+o).val());
php获取
public function editUserImg(){
$param=$this->request->param();
$file = request()->file('img');
$info = $file->move(ROOT_PATH . 'public'. DS . 'uploads');
if($info){
$where['img']=$info->getSaveName();
//压缩图片
$image= \think\Image::open($info);
$image->thumb(150,150)->save('uploads/'.$where['img']);
if($param['option_id'] != 'undefined'){
$val=db('vote_option')->where('id',$param['option_id'])->update($where);
$url=db('vote_option')->where('id',$param['option_id'])->find();
}else{
$val=db('vote_option')->insertGetId($where);
$url=db('vote_option')->where('id='.$val)->find();
}
return json_encode($url);
}else{
return $file->getError();
}
}
补充:ajax利用formdata上传图片还需要注意两个点, contentType与processData必须为false
$.ajax({
url:"",
type:'post',
data:formdata,
contentType:false,
processData:false,
success:function (res){
console.log(res);
}
})