easyui+SpringMVC添加图片

2019-10-30 11:59:35 浏览数 (1)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/luo4105/article/details/50760583

在SpringMVC添加图片四个步骤

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

代码语言:javascript复制
</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,才能完整的传递文件数据,进行下面的操作.例子:

代码语言:javascript复制
<form id="fm" method="post" enctype="multipart/form-data">

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

代码语言:javascript复制
public Map<String, Object> save(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request,MatrielHuman matrielHuman) {
}

4.放在文件夹

代码语言:javascript复制
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

代码语言:javascript复制
<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" οnclick="save()">确定</a>
						  
				<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" οnclick="javascript:$('#dlg').dialog('close')">取消</a>
			</td>
		</tr>
	</table>
</form>

controller

代码语言:javascript复制
@RequestMapping("add_TTestImg")
@ResponseBody
public 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);
	// 调用service
	tTestImgService.addTTestImg(params);
	return AjaxUtils.reponseToJson("添加", true);
}

0 人点赞