<link href="../fileinput/fileinput.min.css" rel="stylesheet">
<script src="../fileinput/fileinput.min.js">
<script src="../fileinput/zh.js"></script>
html代码:
<input> class="fileinput"会自动渲染,form必须添加enctype="multipart/form-data"属性
<form action="" method="post" target="_parent" enctype="multipart/form-data">
<input id="fileinput" type="file" name="img" />
</form>
初始化:
var control = $("#fileinput");
//初始化fileinput
control.fileinput({
language: 'zh', //设置语言
allowedFileExtensions : ['jpg', 'png','gif','jpeg'],//接收的文件后缀
showUpload: false, //是否显示上传按钮
showRemove: false, //是否显示删除按钮
showCaption: true,//是否显示标题
browseClass: "btn btn-primary", //按钮样式
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
});
编辑页面加载默认图片:
control.fileinput('refresh', {
initialPreview: [ //预览图片的设置
"<img src='${currGoods.img}' width='256px' height='160px' class='file-preview-image'>",
],
});
spring mvc上传图片:
spring-mvc.xml配置文件
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="5242880" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
java后台代码
//保存配置
@RequestMapping("/submit")
public void counselorSubmit(MultipartFile goodsImg,QisbaoGoods goods,HttpServletRequest request, HttpServletResponse response
,Model model) throws ServletException, IOException{
System.out.println("===xxoo==="+goods.toString());
//原始名称
String originalFilename = goodsImg.getOriginalFilename();
// 上传图片
if (goodsImg != null && originalFilename != null
&& originalFilename.length() > 0) {
// 新的图片名称
String newFileName = Tools.createRandomName("Q")
+ originalFilename.substring(originalFilename
.lastIndexOf("."));
// 存储图片的物理路径
String pic_path = "";
String imgUpload=ConfigUtils.getConfigValues("imgUpload");
String virtualPath = "/upload/qisbao/"+newFileName;
if("/wyfx".equals(imgUpload)){
pic_path = imgUpload+ virtualPath;
}else{
pic_path = request.getSession().getServletContext().getRealPath("/")+virtualPath;
pic_path = pic_path.replace("/", "\\");
}
// 新图片
File newFile = new File(pic_path);
// 将内存中的数据写入磁盘
goodsImg.transferTo(newFile);
// 将新图片名称写到itemsCustom中
goods.setImg(virtualPath);
}
if(goods.getId()==null){
goods.setGoodNo(Tools.createRandomName("Q"));
goodsMapper.insert(goods);
}else{
goodsMapper.updateByPrimaryKeySelective(goods);
}
response.sendRedirect("goods.action");
}