js single image upload

 

front 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('上传失败');
}
});

}
});

 

backend 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{
// Upload failed to get error message
$msg = $file->getError();
$data['error']=2;
$ data['msg']=$msg;
}
}

echo json_encode($data);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325302303&siteId=291194637