layui的多图片上传

踩了很多坑,特此记录。

layui的upload模块,在上传多图片时,其实就是一个一个上传。

后台(java为例子)接收方式

@RequestParam MultipartFile file在这里插入图片描述

出现了conveter 这个转换异常就是下面解决办法

No converter found for return value of type: class java.util.HashMap

POM.XML的依赖(一定要记得加上!)

<!-- springMVC的json转换依赖包 -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.9.9</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-core</artifactId>
		<version>2.9.9</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-annotations</artifactId>
		<version>2.9.9</version>
	</dependency>

layui.upload要求我们返回json格式给客户端,所以我们需要数据格式化。

String jsonResult = JSON.toJSONString(model);


以下是完整后端代码

@RequestMapping("uploadImg")
	@ResponseBody
	public void uploadImg(@RequestParam MultipartFile file, ModelMap model,HttpServletResponse response) {
		try {
			if (!file.isEmpty()) {
				String originalFilename = file.getOriginalFilename();
				long size = file.getSize();
				System.out.println("上传文件名为" + originalFilename + ",上传大小为" + size);
				// uuid是机器码,是唯一的
				String uuid = UUID.randomUUID().toString();
				// 获取后缀名
				int lastIndexOf = originalFilename.lastIndexOf(".");
				String substring = originalFilename.substring(lastIndexOf);
				// 设置保存路径
				String filenames = "C:\\Users\\YT\\eclipse-workspace\\weibao\\src\\main\\resources\\uploadImg\\"
						+ originalFilename + uuid + substring;
				File files = new File(filenames);
				FileOutputStream fos = new FileOutputStream(filenames);
				IOUtils.copy(file.getInputStream(), fos);
				model.put("code", 200);
				model.put("msg", "success");
			} else {
				model.put("msg", "error");
				model.put("code", 0);
			}
		} catch (Exception e) {
			model.put("msg", "error");
			model.put("code", 0);
			e.printStackTrace();
		}finally {
			String jsonResult = JSON.toJSONString(model);
			response.setContentType("text/html;charset=UTF-8");
			renderData(response, jsonResult);
		}
	}
	/**
	 * 通过PrintWriter将响应数据写入response,ajax可以接受到这个数据
	 * 
	 * @param response
	 * @param data
	 */
	private void renderData(HttpServletResponse response, String data) {
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(data);
		} catch (IOException ex) {
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}
	}
发布了53 篇原创文章 · 获赞 0 · 访问量 4135

猜你喜欢

转载自blog.csdn.net/qq_36453423/article/details/104256963
今日推荐