1.HTML页面:
<form class="layui-form" action="/Home/TraveThink" method="post" enctype="multipart/form-data">
<div class="set_btn layui-upload" id="_j_cover_do">
<a role="button" title="设置头图" class="a_set _j_addtoppiclabel" id="img"><i></i><span>设置头图</span></a>
<img id="imgupload" src="~/images/lvyoutop.jpg" width="1000" height="480" />
<input type="hidden" name="TravelInformationImgurl" id="imgurl" value="" />
</div>
</form>
图片上传必备: method=“post” enctype=“multipart/form-data”
js 部分:
<script src="~/layui/layui.js"></script>
<script>
layui.use(['form', 'layedit', 'laydate', 'upload'], function (maxval) {
var form = layui.form
, layer = layui.layer
, layedit = layui.layedit
, laydate = layui.laydate;
var $ = layui.jquery
, upload = layui.upload;
//'form', 'layedit', 'laydate', 可以不要,不受影响。
//调用文件上传文档,
//普通图片上传
var uploadInst = upload.render({
elem: '._j_addtoppiclabel'
, url: '/Home/imaesgUpload' //改成您自己的上传接口
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#imgupload').attr('src', result); //图片链接(base64)
});
}
, done: function (res) {
console.log(res);
//如果上传失败
if (res.code == 200) {
$('#imgupload').attr('src', "/images/" + res.data);
$("#imgurl").val(res.data);
return layer.msg('上传成功');
}
//上传成功
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function () {
uploadInst.upload();
});
}
});
});
</script>
后台实现方法:
public ActionResult imaesgUpload()
{
if (Request.Files.Count > 0)
{
//取出第一个文件
var file = Request.Files[0];
//取出用户上传的文件名
String filename = file.FileName;
if (!String.IsNullOrWhiteSpace(filename))
{
string suf = filename.Substring(filename.LastIndexOf('.'));
string newfilename = Guid.NewGuid().ToString().Replace("-", "") + suf;
String url = Server.MapPath("~/images/" + newfilename);
file.SaveAs(url);
string result = newfilename;
return Json(new { code = 200, data = result });
}
}
return Json(new { code = 500 });
}
}
}
最终实现效果:
点击头图,进入选择:
选中图片进行上传
最终实现:
不会的可以留言,基本在线哦!