layUi

一、layUi前台实现

网站

https://www.layui.com/

html代码中

<div class="layui-upload">
  <div class="layui-upload-list">
  <img id="uploadIMG" style="width: 100px;height: 100px;" src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=145692761,4091651670&fm=26&gp=0.jpg"
  class="layui-upload-img" id="demo1">
  </div>
</div>

导入+实现


<link rel="stylesheet" type="text/css" href="js/layui/css/layui.css" />
<script src="js/layui/layui.js" type="text/javascript" charset="utf-8"></script>

<script type="text/javascript">
  // 必须引入element 才有js效果
  layui.use(['element','upload'], function() {
	var upload = layui.upload;
    //普通图片上传
    var uploadInst = upload.render({
      elem: '#uploadIMG', // 对应上面的id 用于点击触发
      url: 'http://localhost:8080/myhouse/upload', //改成您自己的上传接口
      before: function(obj) { // before 在什么什么之前
        //预读本地文件示例,不支持ie8
        obj.preview(function(index, file, result) {
          $('#uploadIMG').attr('src', result); //图片链接(base64)
        });
      },
      done: function(res) {
        // 上传表单
        $('[name=userphoto]').val(res.img);
        //上传成功
      }
    });
  });
</script>

二、文件上传layui.upload后台实现

实现思路

1、在本地中查找图片;
	-》 上传到服务器中
	=》 上传成功到服务器返回 该图片名
	=》 把该图片名set到 hidden文件提交表单
	=》 把数据库中用户的头像引用 该图片名 因为已经在服务器中了
 <!-- 上传文件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件的最大尺寸为10MB -->
		<property name="maxUploadSize">
			<value>10485760</value>
		</property>
		<!--设置编码,与jsp页面编码一致-->
		<property name="defaultEncoding">
			<value>UTF-8</value>
		</property>
	</bean>
    

导入tool工具类

public class Tool {
	
	// 生成唯一字符
	public static String createUUID() {
		// replace 替换
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 单文件上传
	 * 
	 * @param request
	 *            请求获取项目路径
	 * @param fileImage
	 *            上传的文件
	 * @param imgRoot
	 *            图片根目录
	 * @param isRandom
	 *            是否产生新图片名
	 * @throws Exception
	 */
	public static String upload(HttpServletRequest request,
			MultipartFile fileImage, String imgRoot, boolean isRandom)
			throws Exception {
		String returnRundomFileName = "";
		System.out.println(fileImage);
		if (fileImage != null && !fileImage.isEmpty()) { // 检查文件是否为空,空表示未上传,非空则保存文件
			String ProjectPath = request.getSession().getServletContext()
					.getRealPath("/" + imgRoot + "/"); // 项目路径+图片根目录
			String oldName = fileImage.getOriginalFilename(); // 原文件名6.pnh
			String newFilename = oldName;
			// File.separator = ‘/’
			if (isRandom) {
				String extension = FilenameUtils.getExtension(oldName); // 后缀
				returnRundomFileName = 	System.currentTimeMillis() + "." + extension;												// png
				newFilename = ProjectPath + File.separator
						+ returnRundomFileName; // 项目图片根路径+随机数新名字+后缀
			}
			File targetFile = new File(newFilename);
			System.out.println("图片路径"+targetFile);
			// fileImage 当前图片 复制 到 根
			fileImage.transferTo(targetFile);
		}
		return returnRundomFileName;
	}

	/**
	 * 重载用来上传多个文件
	 * 
	 * @param request
	 *            请求获取项目路径
	 * @param fileImages
	 *            上传的数组文件
	 * @param imgRoot
	 *            图片根目录
	 * @param isRandom
	 *            是否产生新图片名
	 * @throws Exception
	 */
	public static List<String> upload(HttpServletRequest request,
			MultipartFile[] fileImages, String imgRoot, boolean isRandom)
			throws Exception {
		System.out.println("文件:"+fileImages);

		List<String> files = new ArrayList<>();
//		for (MultipartFile fileImage : fileImages) {
//			files.add(upload(request, fileImage, imgRoot, isRandom));
//		}
		return files;
	}

	/**
	 * 文件下载
	 * @param fileName
	 * @param imgRoot
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public static void download(String fileName,String imgRoot, HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置内容类型-二进制
		response.setContentType("multipart/form-data");
		// 设置响应头--下载的方式处理文件
		response.setHeader("content-disposition", "attachement;filename="+ fileName);
		// 获取文件的物理路径
		String path = request.getSession().getServletContext()
				.getRealPath("/"+imgRoot+"/" + fileName);
		// 读文件、输入流
		File file = new File(path);
		FileInputStream inputStream = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		byte[] b = new byte[1024];
		int length;
		// 循环将文件内容读取,并写入到输入流
		while ((length = inputStream.read(b)) > 0) {
			os.write(b, 0, length);
		}
		inputStream.close();
	}
	/**
	 * 解决跨域
	 * @param request
	 * @param res
	 * @param chain
	 * @throws Exception
	 */
	public static void crossDomain(ServletRequest request,ServletResponse res, FilterChain chain)throws IOException, ServletException{
		HttpServletResponse response = (HttpServletResponse) res;
		/* 允许跨域的主机地址 */
		response.setHeader("Access-Control-Allow-Origin", "*");  
		/* 允许跨域的请求方法GET, POST, HEAD 等 */
		response.setHeader("Access-Control-Allow-Methods", "*");  
		/* 重新预检验跨域的缓存时间 (s) */
		response.setHeader("Access-Control-Max-Age", "3600");  
		/* 允许跨域的请求头 */
		response.setHeader("Access-Control-Allow-Headers", "*");  
		/* 是否携带cookie */
		response.setHeader("Access-Control-Allow-Credentials", "true");  
		chain.doFilter(request, response);
	}
	
	// 测试
	public static void main(String[] args) {

	}
}

controller 调用

// 上传
    @RequestMapping(value="/admin/upload",method= RequestMethod.POST,produces="application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest request, MultipartFile file) throws Exception {
        Map<String, Object> img = new HashMap<>();
        img.put("img", Tool.upload(request,file,"static/pictures/user",true));
        return img;
    }

富文本

quilljs

https://quilljs.com/

ueditor

打开里面有index demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值