ajax上传图片
前几天没事自己做了小demo,写的不好,请大家多多指教
第一步:
首先想要使用ajaxFileUpload插件必须要在html中引入两个js(具体的URI根据自己的项目结构进行调整)
<script src="${basePath}/resources/adminlte/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="${basePath}/resources/bussiness/plugins/wysiwyg/ajaxfileupload.js"></script>
第二步:
上传的input的html的代码
<li class="mui-table-view-cell mui-media" id="uploadBtn" onclick="" >
<a class="mui-navigate-right mui-disabled">
<div class="form-group" style="padding: 10px 0;">
<label for="name" class="col-sm-3 control-label">上传头像</label>
<div class="col-sm-8">
<input type="hidden" name="upload" id="avatr" value="{{$person->img}}">
<img id="image" class="cover-radius" src="http://www.iwantbeauty.cn/group1/M00/00/80/rBGNTVwSE4CAGJt5AACGL9lSKyI348.jpg"
style="cursor: pointer;width: 50px;position: absolute; right: 65px;top: 5px;border-radius: 50%;" />
<input id="picture_upload" name="mypic" type="file" onchange="upload_cover(this)"
style="position: absolute; right: 0px; top: 0px; width: 100%; height: 100%; opacity: 0; cursor: pointer;"/>
<small class="help-block cover-tips" style="color: #dd4b39;display: none;">请上传照片</small>
</div>
</div>
</a>
</li>
第三步:
js的代码,在js中我加入了图片的格式的验证
function ajax_upload(feid, callback) { //具体的上传图片方法
if (image_check(feid)) { //自己添加的文件后缀名的验证
$.ajaxFileUpload({
fileElementId: feid, //需要上传的文件域的ID,即<input type="file">的ID。
url: '/upload', //后台方法的路径
type: 'post', //当要提交自定义参数时,这个参数要设置成post
dataType: 'json', //服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
secureuri: false, //是否启用安全提交,默认为false。
async : true, //是否是异步
success: function(data) { //提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
var img= data.data[0];
$('#image').attr('src',img);
$('#avatr').val(img);
if (callback) callback.call(this, data);
},
error: function(data, status, e) { //提交失败自动执行的处理函数。
console.error(e);
}
});
}
}
function image_check(feid) { //自己添加的文件后缀名的验证
var img = document.getElementById(feid);
return /.(jpg|png|gif|bmp|jpeg)$/.test(img.value)?true:(function() {
modals.info('图片格式仅支持jpg、png、gif、bmp、jpeg格式,且区分大小写。');
return false;
})();
}
第四步:
上传图片的后台的代码:我这是用laravel框架写的
如果您没有建文件夹则使用php artisan storage:link
public function imgUpload(Request $request)
{
if ($request->isMethod('POST')) {
$file = $request->file('mypic');
//判断文件是否上传成功
if ($file->isValid()) {
//获取原文件名
$originalName = $file->getClientOriginalName();
//扩展名
$ext = $file->getClientOriginalExtension();
//文件类型
$type = $file->getClientMimeType();
//临时绝对路径
$realPath = $file->getRealPath();
$size = $file->getSize();
$filename = md5(time()).'-'.uniqid().".jpg";
$bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
$arr = array ('data'=>[asset('storage/'.$filename)],'errno'=>0);
return $arr;
}
}
}
下载插件https://codeload.github.com/carlcarl/AjaxFileUpload/zip/master