layui图片上传按钮按着没反应_图片上传——layui+ssm

本文介绍了如何使用layui和SSM实现图片上传功能,包括前端layui弹出层显示表单、文件上传配置、Controller接收文件并保存到指定目录,以及数据库中存储文件名的处理。
摘要由CSDN通过智能技术生成

废话不多说,直接上步骤

先看看效果:

上传成功:

导入相关依赖

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值