废话不多说,直接上步骤
先看看效果:
上传成功:
导入相关依赖
commons-fileupload
commons-fileupload
1.3.3
javax.servlet
javax.servlet-api
4.0.1
注:servlet是为了写出文件的时候获取项目路径。
前端利用layui的弹出层显示表单
curIndex = layer.open({
type: 1,
area: ['300px', '300px'],
title: "增加/修改图片信息",
fixed: false, //不固定
maxmin: true,
shadeClose: false,
content: $('#car_image')
});
//表单值
form.val("upload_image", {
"car_id": data.car_id
})
}
注:content属性是打开的那个div
图片上传html
请选择需要上传的图片
编号:
选择文件
开始上传
(重要)文件上传配置:
Controller接收并输出到目录
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") CommonsMultipartFile file,@RequestParam("carId") int carId, HttpServletRequest request, Model model) throws IOException {
JsonUtil fileJson = new JsonUtil();
ObjectMapper objectMapper = new ObjectMapper();
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,返回失败!
if ("".equals(uploadFileName)){
fileJson.setCode(1);
return objectMapper.writeValueAsString(fileJson);
}
//获取上传文件名的后缀
String[] splitStr = uploadFileName.split("\\.");
String suffix = splitStr[splitStr.length - 1];
String fileName = System.currentTimeMillis() + "." + suffix;
//上传路径保存设置
String path = request.getSession().getServletContext().getRealPath("/car_images");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(new File(realPath,fileName));
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
int i = carService.addFile(carId, fileName);
if (i >0){
fileJson.setCode(0);
return objectMapper.writeValueAsString(fileJson);
}else {
fileJson.setCode(1);
return objectMapper.writeValueAsString(fileJson);
}
}
数据库存放的是该图片的名称+后缀,用于前端显示图片。
数据及图片显示就是layui的table。
标签:String,fileJson,layui,ssm,file,new,上传,objectMapper
来源: https://www.cnblogs.com/Mr-hanexp/p/13304837.html