Layui 的上传是最常用的, 不可或缺, 记录一下代码, 以后复制都能用!!
1.前端HTML:
修改头像
点击上传图片,或将图片拖拽到此处
2.前端js:
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中, 和表单一起提交到后台, 此处略..
/* console.log(res.data.src);*/
window.parent.uploadHeadImage(res.data.src);
var demoText = $(‘#demoText‘);
demoText.html(‘上传成功!!!‘);
}
, error: function () {
//演示失败状态,并实现重传
var demoText = $(‘#demoText‘);
demoText.html(‘上传失败 重试‘);
demoText.find(‘.demo-reload‘).on(‘click‘, function () {
uploadInst.upload();
});
}
});
element.init();
});
3.页面展示:
4.后台SpringMVC 接受:
/**
个人信息上传
@return {Result}
*/
@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 map2=new HashMap<>();
Map map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
map2.put("src","../../../static"+uploadDir + dateStr + "." + prefix);
return map;
}
5.关于表单请求, 正常使用layui的表单上传就可以了.. 这里就不写了, 太简单了, 我其它博客有写,请去翻阅,嗯 ,就这样.......