js部分
//保存触发函数
function pic_save() {
var bname = $('input[name = "bname"]').val(); //获取数据
var cid = $('input[name = "cid"]').val(); //获取数据
var blogo = document.getElementById('blogo').files[0];//获取图片file
alert(bname);
var formData=new FormData(); //创建formDate
formData.append("file",$("#blogo")[0].files[0]); //添加数据
formData.append("cid",cid);//也可以传递其他字段
formData.append("bname",bname);
$.ajax({ //ajax响应
type:"post",
url:"upload",
data: formData,
contentType: false,
processData: false,
success: function (result) {
if (result.code === '200') {
bootbox.alert("成功");
window.location.reload();
}
}
})
}
java部分
@RequestMapping("/upload")
@ResponseBody
public Result uploadFile(MultipartFile file, String bname, String cid) throws IOException {
Result result = new Result();
try {
//获取文件名
String fileName = file.getOriginalFilename();
//保存图片的路径
String filePath = "F:/QQReserve/myshop/src/main/resources/static/image/";
File dest = new File(filePath + fileName);
//保存图片
file.transferTo(dest);
System.out.println(fileName);
Brand brand = new Brand();
brand.setBname(bname);
brand.setBlogo(fileName);
int id = Integer.parseInt(cid);
brand.setCid(id);
//插入
brandMapper.insertBrand(brand);
result.setCode(Resource.SUCCESS);
result.setMsg("新增成功");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
html部分
<img src="/image/${bl.blogo}" width="160" alt="" />