• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
#define wzz
博客园    首页    新随笔    联系   管理    订阅  订阅
上传图片

1.一个页面中只上传一张图片

<script type="text/javascript" src="${contextPath}/resources/web/js/AjaxFileUploaderV2.1/ajaxfileupload.js"></script>

<input id="icon" name="icon" htmlEscape="false" type="hidden" />
							<label>
								<img id="iconimg" name="iconimg" src="${contextPath}/resources/web/images/tuo.png" />
								<input size="2" type="file" hidden="hidden" id="uploadfile" name="uploadfile" onchange="ajaxFileUpload()" style="display: none" />
							</label>


function ajaxFileUpload() {
		
		var uploadUrl = encodeURI(encodeURI("${contextPath}/commons/uploadimgs"));
		if (uploadUrl != "") {
			
			$.ajaxFileUpload({
				url : uploadUrl,
				secureuri : false,
				fileElementId : 'uploadfile',
				dataType : 'text',
				success : function(data, status) {
					var dataset = jQuery.parseJSON(jQuery(data).text());
					if (dataset.ret == "ok") {
						
						$("#spuicon").attr("src", dataset.url);
						$("#puicon").val(dataset.url);
						
					} else if (dataset.ret == "empty") {
						showmsg(0, '没有选择图片,请先选择图片!');
					} else {
						shomsg(0, '图片上传失败,请重试!!');
					}
				},
				error : function(data, status, e) {
					console.log(e);
					console.log(data);
					showmsg(0, '图片上传失败,请重试!!');
				}
			});
		}
	}

  2.上传多张图片

<script type="text/javascript" src="${contextPath}/resources/web/js/AjaxFileUploaderV2.1/ajaxfileupload.js"></script>

<input id="icon" name="icon" htmlEscape="false" type="hidden"/>
							<label>
								<img id="iconimg" name="iconimg" src="${contextPath}/resources/web/images/tuo.png" />
								<input size="2" type="file" hidden="hidden" id="uploadfile0" name="uploadfile" onchange="ajaxFileUpload(0)" style="display: none" />
							</label>


<script language="javascript">
	$(document).ready(function() {

	});

	function ajaxFileUpload(id) {

		var uploadUrl = encodeURI(encodeURI("${contextPath}/commons/uploadimgs"));
		if (uploadUrl != "") {
			$.ajaxFileUpload({
				url : uploadUrl,
				secureuri : false,
				fileElementId : 'uploadfile' + id,
				dataType : 'text',
				success : function(data, status) {
					var dataset = jQuery.parseJSON(jQuery(data).text());
					if (dataset.ret == "ok") {

						if (id == 0) {
							$("#scicon").attr("src", dataset.url);
							$("#cicon").val(dataset.url);
						} else if (id == 1) {
							$("#sicon").attr("src", dataset.url);
							$("#icon").val(dataset.url);
						} else if (id == 2) {
							$("#slicon").attr("src", dataset.url);
							$("#licon").val(dataset.url);
						}
					} else if (dataset.ret == "empty") {
						showmsg(0, '没有选择图片,请先选择图片!');
					} else {
						shomsg(0, '图片上传失败,请重试!!');
					}
				},
				error : function(data, status, e) {
					console.log(e);
					console.log(data);
					showmsg(0, '图片上传失败,请重试!!');
				}
			});
		}
	}

	function doSave() {

		ajax_get("${contextPath}/web/projectsave", $("#editForm").serialize(), function(data) {

			if (data.errorMessage) {
				showmsg(0, data.errorMessage);
			} else {
				showmsg(1, "处理成功!");
			}
		});
	}
</script>

  

后台controller:

CommonsController:
@RequestMapping("/commons")
@Controller
public class CommonsController {
	@RequestMapping(value = "/uploadimg0")
	@ResponseBody
	public Map<String, Object> uploadimg0(@RequestParam(value = "uploadfile0") MultipartFile uploadfile, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();

		map = saveImg(uploadfile);
		return map;
	}

	@RequestMapping(value = "/uploadimg1")
	@ResponseBody
	public Map<String, Object> uploadimg1(@RequestParam(value = "uploadfile1") MultipartFile uploadfile, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();

		map = saveImg(uploadfile);
		return map;
	}

	@RequestMapping(value = "/uploadimg2")
	@ResponseBody
	public Map<String, Object> uploadimg2(@RequestParam(value = "uploadfile2") MultipartFile uploadfile, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();

		map = saveImg(uploadfile);
		return map;
	}

	private Map<String, Object> saveImg(MultipartFile uploadfile) {
		Map<String, Object> map = new HashMap<String, Object>();

		if (uploadfile != null && !uploadfile.isEmpty()) {
			String suploadPath = WebConstants.DEFAULT_IMG_PATH + AoConstants.JOIN_URL + DateUtil.getCurrentDate("yyyyMM") + AoConstants.JOIN_URL
					+ DateUtil.getCurrentDate("dd") + AoConstants.JOIN_URL + DateUtil.getCurrentDate("HH") + AoConstants.JOIN_URL;
			String realPath = WebConstants.DEFAULT_FILE_DIRECTORY + suploadPath;

			String originFileName = uploadfile.getOriginalFilename(); // 文件原名称
			originFileName = CommonUtil.changeFileName(originFileName);

			try {
				CommonUtil.uploadFile(uploadfile, realPath, originFileName);
				map.put("ret", "ok");
				map.put("url", (WebConstants.DEFAULT_URL_HTTP + suploadPath + originFileName));
			} catch (Exception ex) {
				map.put("ret", "error");
				ex.printStackTrace();
			}
		} else {
			map.put("ret", "empty"); // 未选择文件
		}
		return map;
	}

	@RequestMapping(value = "/uploadimgs", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadimg(@RequestParam(value = "uploadfile") MultipartFile[] uploadfile, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();

		if (uploadfile == null || uploadfile.length == 0) {
			map.put("ret", "empty"); // 未选择文件
			return map;
		}

		for (MultipartFile uploadfile1 : uploadfile) {
			if (uploadfile1 != null && !uploadfile1.isEmpty()) {
				String suploadPath = WebConstants.DEFAULT_IMG_PATH + AoConstants.JOIN_URL + DateUtil.getCurrentDate("yyyyMM") + AoConstants.JOIN_URL
						+ DateUtil.getCurrentDate("dd") + AoConstants.JOIN_URL + DateUtil.getCurrentDate("HH") + AoConstants.JOIN_URL;
				String realPath = WebConstants.DEFAULT_FILE_DIRECTORY + suploadPath;

				String originFileName = uploadfile1.getOriginalFilename(); // 文件原名称
				originFileName = CommonUtil.changeFileName(originFileName);

				try {
					CommonUtil.uploadFile(uploadfile1, realPath, originFileName);
					map.put("ret", "ok");
					map.put("url", (WebConstants.DEFAULT_URL_HTTP + suploadPath + originFileName));
				} catch (Exception ex) {
					map.put("ret", "error");
					ex.printStackTrace();
				}
			} else {
				map.put("ret", "empty"); // 未选择文件
			}
		}
		return map;
	}

	@RequestMapping(value = "/uploadimg")
	@ResponseBody
	public Map<String, Object> uploadimg(@RequestParam(value = "uploadfile") MultipartFile uploadfile, HttpServletRequest request,
			HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();

		if (uploadfile != null && !uploadfile.isEmpty()) {
			String suploadPath = WebConstants.DEFAULT_IMG_PATH + AoConstants.JOIN_URL + DateUtil.getCurrentDate("yyyyMM") + AoConstants.JOIN_URL
					+ DateUtil.getCurrentDate("dd") + AoConstants.JOIN_URL + DateUtil.getCurrentDate("HH") + AoConstants.JOIN_URL;
			// String realPath = request.getSession().getServletContext().getRealPath(uploadPath) + AoConstants.JOIN_URL;
			String realPath = WebConstants.DEFAULT_FILE_DIRECTORY + suploadPath;

			String originFileName = uploadfile.getOriginalFilename(); // 文件原名称
			originFileName = CommonUtil.changeFileName(originFileName);

			try {
				// 这里使用Apache的FileUtils方法来进行保存
				// FileUtils.copyInputStreamToFile(uploadfile.getInputStream(), new File(realPath, originFileName));

				CommonUtil.uploadFile(uploadfile, realPath, originFileName);
				map.put("ret", "ok");

				// String basePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
				// System.out.println(ContextLoader.getCurrentWebApplicationContext());
				// System.out.println(ContextLoader.getCurrentWebApplicationContext().getServletContext().getContextPath());
				// System.out.println(basePath);

				map.put("url", (WebConstants.DEFAULT_URL_HTTP + suploadPath + originFileName));
			} catch (Exception ex) {
				map.put("ret", "error");
				ex.printStackTrace();
			}
		} else {
			map.put("ret", "empty"); // 未选择文件
		}
		return map;
	}
}

  

posted on 2016-01-07 13:26  #define wzz  阅读(156)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3