JS图片上传实现先逻辑判断再弹出上传窗口

项目需求:需要先进行逻辑判断,如果满足条件则弹出上传窗口选择图片上传,否则不弹出上传窗口,提示alert("原因!");

 

1、前端代码:





Demo


后台代码:

    @RequestMapping(value = "/fileuploadBatch", method = RequestMethod.POST)
	@ResponseBody
	public C2BResponseBody fileuploadBatch(HttpServletRequest request, String id) {
		C2BResponseBody responseBody = null;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator iter = multipartRequest.getFileNames();
		MultipartFile file = null;
		while (iter.hasNext()) {
			file = multipartRequest.getFile(iter.next());
		}

		String filePath = "";
		String originalFilename = file.getOriginalFilename();
		try {
			String fileType = originalFilename.substring(
					originalFilename.lastIndexOf(".") + 1).toLowerCase();

			float bb = bytes2kb(file.getSize());

			if (bb > 10) {
				throw new Exception("文件上传失败,最大上传大小为10M。");
			}
            // 调用上传到服务器接口
			filePath = mediaService.media(file.getInputStream(),fileType);
			if (StringUtils.isEmpty(filePath)){
				responseBody = new C2BResponseBody();
				responseBody.setErrorCode("000001");
				responseBody.setErrorMessage("存储失败!");
				return responseBody;
			}
			responseBody.setErrorMessage(Configure.getConfigFromZookeeper(GaguConstant.IMG_DOMAIN) + filePath);
		} catch (Exception e) {
			responseBody = new C2BResponseBody();
			responseBody.setErrorCode("000001");
			responseBody.setErrorMessage(e.getMessage());
		}
		return responseBody;
	}

public static float bytes2kb(long bytes) {
		BigDecimal filesize = new BigDecimal(bytes);
		BigDecimal megabyte = new BigDecimal(1024 * 1024);
		float returnValue = filesize.divide(megabyte, 2, 0)
				.floatValue();

		return returnValue;
	}

C2BResponseBody 为自己要返回的对象;

你可能感兴趣的:(File,文件上传)