图片上传——layui+ssm
废话不多说,直接上步骤
-
先看看效果:
上传成功: -
导入相关依赖
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
注: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
<!--图片上传-->
<div id="car_image" style="display:none">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>请选择需要上传的图片</legend>
</fieldset>
<form id="upload_image" lay-filter="upload_image" class="layui-form" style="display: none">
编号:<input type="text" name="car_id" value="" id="car_id_image" class="layui-input-inline"/>
</form>
<div class="layui-upload">
<button type="button" class="layui-btn layui-btn-normal" id="pickFile">选择文件</button>
<button type="button" class="layui-btn" id="upload">开始上传</button>
</div>
</div>
- (重要)文件上传配置:
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和前端页面的一致 -->
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
- Controller接收并输出到目录
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") CommonsMultipartFile file,@RequestParam("carId") int carId, HttpServletRequest request, Model model) throws IOException {
JsonUtil<FileUp> fileJson = new JsonUtil<FileUp>();
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。