ajax文件上传

需求:

通过ajax异步方式上传图片,上传成功后做些操作

实现:

js部分:

引入:

<script src="http://js.linkrmb.com/ajax/jquery.upload.js" type="text/javascript">
</script>

代码:

function doUpload() {
	// 上传方法
	$.upload({
			// 上传地址
			url: '${basePath}upload/img', 
			// 文件域名字
			fileName: 'filedata', 
			// 上传完成后, 返回json, text
			dataType: 'json',
			// 上传之前回调,return true表示可继续上传
			onSend: function() {
					return true;
			},
			// 上传之后回调
			onComplate: function(data) {
		           $("#imgurl").val(data.msg.url);
		           $("#imgname").val(data.msg.id);
			}
	});
}

html部分:

<tr>
			<td width="10%" >
				封面图片:
			</td>
			<td width="90%">
			    <input id="imgname" name="imgname" type="text" readonly="readonly" >
				<input type="button" onclick="doUpload()" value="点击上传图片">
				<input id="imgurl" name="imgurl" type="hidden" >
			</td>
		</tr>

java部分:

@RequestMapping(value = "/img", method = RequestMethod.POST)
@ResponseBody
public UploadResVo img(HttpServletRequest request) throws Exception {
	 
	UploadResVo resVo = new UploadResVo();
	MsgVo msg = new MsgVo();
	String file = processImg(request, "imageDir");

	msg.setId(file);
	msg.setLocalname(file);
	msg.setUrl(url);
	resVo.setMsg(msg);
	return resVo;
}

private String processImg(HttpServletRequest request,String imageDir) throws Exception {
	String uuid = CommonUtils.getUUID();
	request.setCharacterEncoding("UTF-8");
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	List<FileItem> items = upload.parseRequest(request);
	Iterator<FileItem> itr = items.iterator();
	while (itr.hasNext()) {
		FileItem item = (FileItem) itr.next();
		if (item.isFormField()) {
			System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:"
					+ item.getString("UTF-8"));
		} else {
			System.out.println("上传文件的大小:" + item.getSize());
			System.out.println("上传文件的类型:" + item.getContentType());
			System.out.println("上传文件的名称:" + item.getName());
			String file = imageDir + File.separator +uuid+"."+ FilenameUtils.getExtension(item.getName());
			item.write(new File(file));
			return uuid+"."+ FilenameUtils.getExtension(item.getName());
		}
	}
	return uuid;
}

相关推荐