1. 程式人生 > >springmvc圖片上傳後壓縮處理

springmvc圖片上傳後壓縮處理

後臺程式碼:

@RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
	public @ResponseBody
	JsonResult imageUpload(HttpServletRequest request, Model model) {

		LOGGER.info("image upload begin.");

		JsonResult jsonResult = new JsonResult();

		String filePath = request.getParameter("filePath");

		MultipartHttpServletRequest multipartHttpservletRequest = (MultipartHttpServletRequest) request;

		CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartHttpservletRequest.getFile(filePath);

		if (null == multipartFile || multipartFile.isEmpty()) {

			jsonResult.fail("引數非法");

			return jsonResult;

		}

		InputStream in = null;
		ByteArrayOutputStream bos = null;

		try {

			in = multipartFile.getInputStream();

			String fileName = multipartFile.getOriginalFilename();

			bos = new ByteArrayOutputStream();

			Image image = ImageIO.read(in);
			//  圖片壓縮
			BufferedImage tag = new BufferedImage(239,
					127, BufferedImage.TYPE_INT_RGB);

			tag.getGraphics().drawImage(
					image.getScaledInstance(239, 127,
							Image.SCALE_SMOOTH), 0, 0, null);

			if (multipartFile.getOriginalFilename().endsWith(".jpg")) {
				ImageIO.write(tag, "jpg", bos);
			} else if (multipartFile.getOriginalFilename().endsWith(".png")) {
				ImageIO.write(tag, "png", bos);
			} else {
				jsonResult.fail("上傳圖片格式錯誤");
				return jsonResult;
			}

			byte[] bytes = bos.toByteArray();
			
			//這裡根據業務對bytes 做下一步處理		
		
		} catch (Exception ex) {
			
		} finally {
			
		}

		LOGGER.info("image upload end.");

		return jsonResult;

	}
前端:HTML
<input type="file" id="addUploadImage" name="addUploadImage" placeholder="請上傳一張系列圖">

前端:js
$.ajaxFileUpload({
				url : postUrl, // 需要連結到伺服器地址
				secureuri : false,
				type : "POST",
				fileElementId : "addUploadImage", // 檔案選擇框的id屬性,
				data : {
					filePath : "addUploadImage"
				},
				dataType : 'json',
				success : function(result, status) {
					
				},
				error : function(data, status, e) {
					
				}
			});