lauyi 文件上传的详细用法:layui.upload
一。前台代码块:
上传截图
//js控制控件上传
/*
lauyi 文件上传的详细用法:https://www.layui.com/doc/modules/upload.html
*/
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
/*
* 支付宝-转账截图/记录,可上传多张
* */
var aliPay=upload.render({
elem: '#alipay_btn'
,url: '/order/imageUpload' //改成您自己的上传接口
,multiple: true
,choose: function(obj){
var files = obj.pushFile();
//预读本地文件示例,不支持ie8
obj.preview(function(index, file, result){
console.log(index); //得到文件索引
console.log(file);
$('#alipay_photo').show().find('.multifyBox').append(
''
+ ''
+ ''
+''
)
// 删除图片
$("#removePimg"+index).on("click", function(event){
var _that=$(this);
//_that.next('.layui-upload-img').attr('src','')
// _that.parent().remove();
delete files[index];
$(".mlist"+index).remove();
});
//某图片放大预览
$("#layui-uploadimg"+index).on('click',function () {
var width = $("#layui-uploadimg"+index).width();
var height = $("#layui-uploadimg"+index).height();
var scaleWH = width/height;
var bigH = 600;
var bigW = scaleWH*bigH;
if(bigW>900){
bigW = 900;
bigH = bigW/scaleWH;
}
// 放大预览图片
layer.open({
type: 1,
title: false,
closeBtn: 1,
shadeClose: true,
area: [bigW + 'px', bigH + 'px'], //宽高
content: ""
});
});
});
}
,done: function(res){
//如果上传失败
if(res.code > 0){
return layer.msg('上传失败');
}
//得到上传后的url
imageUrl=res.data.url;
//console.log(res.data);
//上传完毕
console.log('上传完毕')
}
});
})
二。后台接口代码:
/**
* 上传图片
* @param file
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/imageUpload")
@ResponseBody
public Object fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
JSONObject jsonObject=new JSONObject();
// 1.上传路径
String path=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\image";
//得到上传图片的文件名
String fileName = file.getOriginalFilename();
String[] s =fileName.split("/");
//得到该图片的名称
String imageName=s[0];
Date date = new Date();
//格式日期转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//得到session中对象
MemberVO memberVO= (MemberVO) request.getSession().getAttribute("member");
//根据用户id、时间戳以及上传图片名称生成图片名称生成新的图片名称
String newImageName=(memberVO.getId()).toString()+sdf.format(date)+fileName;
//生成图片文件
File targetFile = new File(path, newImageName);
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();//创建父级文件路径
targetFile.createNewFile();//创建文件
}
//写入磁盘
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
//返回访问url
String url="http://localhost:8080/static/image/"+newImageName;
jsonObject.put("url",url);
return Result.ok(jsonObject);
}
三。注意点:
1.有关于前台js中,我们只需要修改自己所需要调用的接口,该upload上传控件会把上传的file自动封装成参数传入后台调用接口:
2.后台接口如果需要返回值的话,可以存入JSONObject对象中,再用返回一个Result.ok()状态码,查看该源代码可知,若返回状态码为0表示该接口被被调用其执行成功: 3.前台需要接受值后台传输的值:
四。完成效果
|