js单图片上传

前台js

$("#file0").change(function() {


if (this.files && this.files[0]) {

var objUrl = getObjectURL(this.files[0]);

var data = new FormData($('#form1')[0]);

$.ajax({
url: "{:url('company/upload')}",
type: 'POST',
data: data,
async: false,
dataType: 'JSON',
processData: false,
contentType: false,

}).done(function(ret){
//alert(ret.path_img);
if(ret.error==1){
$('#box_headimg').attr('src',ret.path_img);
}else{
alert('上传失败');
}
});

}
});

后台php

public function upload(){

$file = request()->file('head_img');

$path=str_replace('\\', '/', 'upload/box');

if (!is_dir($path)) {
mkdir($path, 0777,true);
}
// $path=company_coverimg_path('854');

if($file){
$info = $file->move($path);
if($info){
$path_img ='/'.$path.'/'.$info->getSaveName();
$data['path_img']=$path_img;
$data['error']=1;
}else{
// 上传失败获取错误信息
$msg = $file->getError();
$data['error']=2;
$data['msg']=$msg;
}
}

echo json_encode($data);

}

猜你喜欢

转载自www.cnblogs.com/chentailin/p/8991460.html
今日推荐