easyui+SpringMVC添加图片

来源:互联网 发布:echarts 省市区 json 编辑:程序博客网 时间:2024/05/16 14:36
在SpringMVC添加图片四个步骤

1.在前台,输入框类型name="file" class="easyui-filebox"

 
</pre><pre name="code" class="html"><td width="170" colspan="3"><input name="file" class="easyui-filebox" buttonText="选择图片" style="width: 55%;"/></td>


2.前台表单设置,添加enctype="multipart/form-data"作用:表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.例子:

<form id="fm" method="post" enctype="multipart/form-data">


3.后台controller,加上@RequestParam(value = "file", required = false) MultipartFile file,

public Map<String, Object> save(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request,MatrielHuman matrielHuman) {}

4.放在文件夹

String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");String fileName = file.getOriginalFilename();File targetFile = new File(path, fileName);if (!targetFile.exists()) {targetFile.mkdirs();}try {file.transferTo(targetFile);} catch (Exception e) {e.printStackTrace();}

完整的例子

jsp

<form id="fm" method="post" enctype="multipart/form-data"><table width="740" border="0"><tr><td height="48" align="center"><h2>[图片上传测试]</h2></td></tr><tr><td>图片</td><td><input  name="file" class="easyui-filebox" buttonText="选择图片" style="width: 55%;"/></td></tr><span style="white-space:pre"></span><tr align="center"><td height="30" colspan="2" align="center"><a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="save()">确定</a>  <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">取消</a></td></tr></table></form>

controller

@RequestMapping("add_TTestImg")@ResponseBodypublic Map<String, Object> addTTestImg(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, TTestImg form, String jsonpCallback)throws UnsupportedEncodingException {String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");String fileName = file.getOriginalFilename();File targetFile = new File(path, fileName);if (!targetFile.exists()) {targetFile.mkdirs();}try {file.transferTo(targetFile);//图片上传} catch (Exception e) {e.printStackTrace();}form.setImg(request.getContextPath() + "/upload/" + fileName);Map<String, Object> params = new HashMap<String, Object>();// 参数检查params = MapUtil.toMap(form);// 调用servicetTestImgService.addTTestImg(params);return AjaxUtils.reponseToJson("添加", true);}



0 0
原创粉丝点击