踩了很多坑,特此记录。
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);
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);
}
}
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();
}
}
}