一款Bootstrap图片上传预览插件fileinput.js,点击“选择文件”可以选择想要上传的图片文件,选择图片后会自动在预览区域显示预览效果,同时还在下面显示一个“移除”的按钮,可以点击移除选中的图片,下面的“提交”按钮需设置好服务器端接受文件的正确路径后才能使用的。
页面的head部分,需引入两个CSS样式文件,代码如下:
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="css/bootstrap-fileinput.css">
页面的body部分,div容器里放入一个form表单,代码如下:
<div class="container">
<div class="page-header">
<h3>FormData图片上传</h3>
<form>
<div class="form-group" id="uploadForm" enctype='multipart/form-data'>
<div class="h4">图片预览</div>
<div class="fileinput fileinput-new" data-provides="fileinput" id="exampleInputUpload">
<div class="fileinput-new thumbnail" style="width: 200px;height: auto;max-height:150px;">
<img id='picImg' style="width: 100%;height: auto;max-height: 140px;" src="images/noimage.png" alt="" />
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
<div>
<span class="btn btn-primary btn-file">
<span class="fileinput-new">选择文件</span>
<span class="fileinput-exists">换一张</span>
<input type="file" name="pic1" id="picID" accept="image/gif,image/jpeg,image/x-png"/>
</span>
<a href="javascript:;" class="btn btn-warning fileinput-exists" data-dismiss="fileinput">移除</a>
</div>
</div>
</div>
<button type="button" id="uploadSubmit" class="btn btn-info">提交</button>
</form>
</div>
</div>
页面的底部,需引入jQuery库和上传插件,设置好上传的相关参数,代码如下:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap-fileinput.js"></script>
<script type="text/javascript">
$(function () {
//比较简洁,细节可自行完善
$('#uploadSubmit').click(function () {
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url: 'xxx/xxx',
type: 'POST',
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
if(data.status){
console.log('upload success');
}else{
console.log(data.message);
}
},
error: function (data) {
console.log(data.status);
}
});
});
})
</script>
系统已开启自动识别垃圾评论机制,识别到的自动封号,下载出错或者资源有问题请联系全栈客服QQ 1915635791