前端样式
<div class="layui-upload-drag" id="test1">
<i class="layui-icon"></i>
<p>点击上传,或将文件拖拽到此处</p>
</div>
js
var uploadInst = upload.render({
elem: '#test1', //绑定元素,
url: '/newsList/upload',
type: "post",
done: function (res, index, upload) {
//获取后端返回的参数
console.log(res.data.src);
var src = res.data.src;
// 拿到数据后将值赋值给前端
$("#pictures").val(src);
}
});
后端接口
需要拼接成LayUI需要的返回参数
@RequestMapping("/newsList/upload")
@ResponseBody
public Map<String,Object> upload(MultipartFile file, HttpServletRequest request) {
String upload = newsListService.upload(file, request);
HashMap<Object, Object> temp = new HashMap<>();
temp.put("src",upload);
Map<String,Object> map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",temp);
return map;
}
主要代码
由于在服务器中static文件不加载所以直接写道images文件中
public String upload(MultipartFile file, HttpServletRequest request) {
if (!file.isEmpty()) {
try {
// 文件存放服务端的位置
String rootPath = request.getSession().getServletContext().getRealPath("/");
File dir = new File(rootPath + File.separator + "images");
// 判断是否有此路径
if (!dir.exists()) {
dir.mkdir();
}
// 通过时间戳命名文件
long path = System.currentTimeMillis();
// 写入文件的路径
File serverFile = new File(dir.getAbsolutePath()+"/" + path + ".png");
// 写文件到服务器
file.transferTo(serverFile);
return "images/" + path + ".png";
} catch (Exception e) {
return "";
}
} else {
return "";
}
}