Springboot+Layui图片上传以及预览

Posted 蒙面侠1024

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot+Layui图片上传以及预览相关的知识,希望对你有一定的参考价值。

前端html代码

<div class="layui-col-md3" style="margin-left: 150px;margin-top: 100px">
        <div class="layui-upload-list userFace">
            <input id="imgpath" name="imgpath" type="hidden">
            <div class="layui-upload-list uploader-list" id="userFace" style="overflow: auto;width: 300px">
            </div>
        </div>
        <button class="layui-btn layui-btn-primary userFaceBtn" type="button"><i class="layui-icon">&#xe67c;</i> 上传头像
        </button>
</div>

前端js代码

upload.render(
            elem: ".userFaceBtn",
            url: "/file/uploadFile",
            multiple: true,
            done: function (res) 
                var path = res.path;
                $("#userFace").empty();
                $("#userFace").append('<div class=\\"file-iteme\\""><div class=\\"handle\\"></div><img style=\\"width: 120px;height: 140px;\\" src=\\"' + path + '\\"></div>');
                //给隐藏域赋值
                $("#imgpath").val(path);
                imgPath=path;
            
 );

编写配置类,映射本地路径

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer 

	public static final String UPLOAD_IMAGE_PATH="F:\\\\IDEA pojiect\\\\hrm\\\\src\\\\main\\\\resources\\\\static\\\\upload\\\\img";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) 
        //文件磁盘图片url 映射 ,一下位windows下的
        //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
        registry.addResourceHandler("/img/**").addResourceLocations("file:"+UPLOAD_IMAGE_PATH+"\\\\");
    


Controller接收文件代码

@RestController
@RequestMapping("/file")
public class FileController 
	/**
	 * 文件上传
	 */
	@RequestMapping("uploadFile")
	public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) throws IOException 
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		fileName = IdUtil.simpleUUID() +suffix;
		File dest = new File(UPLOAD_IMAGE_PATH + "/" + fileName);
		file.transferTo(dest);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title",fileName);
		map.put("path","/img" + "/" + fileName);
		map.put("code","0");
		return map;
	

实现效果图

以上是关于Springboot+Layui图片上传以及预览的主要内容,如果未能解决你的问题,请参考以下文章

Springboot+Layui图片上传以及预览

基于layUI的图片上传前预览功能的2种实现方式

layui——上传图片,并实现放大预览

基于THINKPHP+layui+Ajax无刷新实现图片上传预览

LayUI上传图片

LayUI上传图片