这篇文章主要介绍了layui如何实现图片上传+表单提交+ Spring MVC,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
1.前端HTML:
<div class="layui-form-item">
<label class="layui-form-label">修改头像</label>
<div class="layui-input-inline uploadHeadImage">
<div class="layui-upload-drag" id="headImg">
<i class="layui-icon"></i>
<p>点击上传图片,或将图片拖拽到此处</p>
</div>
</div>
<div class="layui-input-inline">
<div class="layui-upload-list">
<img class="layui-upload-img headImage" src="http://t.cn/RCzsdCq" id="demo1">
<p id="demoText"></p>
</div>
</div>
</div>
2.前端js:
<script type="text/javascript">
layui.use(["jquery", "upload", "form", "layer", "element"], function () {
var $ = layui.$,
element = layui.element,
layer = layui.layer,
upload = layui.upload,
form = layui.form;
//拖拽上传
var uploadInst = upload.render({
elem: '#headImg'
, url: '/upload/headImg'
, size: 500
, before: function (obj) {
//预读本地文件示例,不支持ie8
obj.preview(function (index, file, result) {
$('#demo1').attr('src', result); //图片链接(base64)
});
}
, done: function (res) {
//如果上传失败
if (res.code > 0) {
return layer.msg('上传失败');
}
//上传成功
//打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
window.parent.uploadHeadImage(res.data.src);
var demoText = $('#demoText');
demoText.html('<span >上传成功!!!</span>');
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span >上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function () {
uploadInst.upload();
});
}
});
element.init();
});
</script>
3.页面展示:
4.后台SpringMVC 接受:
@RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
@ResponseBody
public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (SecurityUtils.getSubject().isAuthenticated() == false) {
return "redirect:/backEnd/login";
}
String prefix="";
String dateStr="";
//保存上传
OutputStream out = null;
InputStream fileInput=null;
try{
if(file!=null){
String originalName = file.getOriginalFilename();
prefix=originalName.substring(originalName.lastIndexOf(".")+1);
dateStr = format.format(new Date());
String filepath = request.getServletContext().getRealPath("/static") + uploadDir + dateStr + "." + prefix;
filepath = filepath.replace("\\", "/");
File files=new File(filepath);
//打印查看上传路径
System.out.println(filepath);
if(!files.getParentFile().exists()){
files.getParentFile().mkdirs();
}
file.transferTo(files);
}
}catch (Exception e){
}finally{
try {
if(out!=null){
out.close();
}
if(fileInput!=null){
fileInput.close();
}
} catch (IOException e) {
}
}
Map<String,Object> map2=new HashMap<>();
Map<String,Object> map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
map2.put("src","../../../static"+uploadDir + dateStr + "." + prefix);
return map;
}
感谢你能够认真阅读完这篇文章,希望小编分享的“layui如何实现图片上传+表单提交+ Spring MVC”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网行业资讯频道,更多相关知识等着你来学习!