Spring Mvc 上傳圖片全部過程

我也是google和百度和很久一點一點弄的……,希望能幫助到你。

直接看代碼吧……

<tr>
     <td align="right">圖片:</td><td>  <form:hidden path="picPath" id="picPath"></form:hidden>
 	  <span id="${uuid}-statusPic" style="color: #666;">
 	  <a href="javascript:void(0)" οnclick="window.smartMenu.insert.replaceString()">預覽</a></span>
 	  <a class="easyui-linkbutton" οnclick="$('#${uuid}-uploadWindow').window('open')">修改</a>
     </td>
</tr>

<!-- 點擊修改調出窗口 -->

<div id="${uuid}-uploadWindow" class="easyui-window" title="圖片上傳" modal="true" resizable="false" collapsible="false" minimizable="false" maximizable="false" closed="true" style="width:520px;height:100px;padding:5px;background: #fafafa;">
		<div class="easyui-layout  with iframe" fit="true">
			<div region="center" border="false" style="padding:10px;background:#fff;border:1px solid #ccc;">
				<form action="menu/SmartMenu.do?action=uploadFile" method="post" enctype="multipart/form-data" style="color: #666;" id="${uuid}-tforma">
				   <input type="hidden" name="picPath" id="${uuid}-picPath" value="${command.picPath}"/>
				      圖片路徑: <input type="file" name="itemPic" alt="" accept="image/*" id="${uuid}-itemPic">圖片大小不超過2M<input  class="easyui-linkbutton" type="submit" value="上傳">
                 </form>
			</div>
		</div>
	</div>

<!-- 頁面剛剛加載時調用 -->

init: function(uuid) {
    // this.identifier 是設定的全局變量,uuid是頁面加載時的唯一編碼
    this.identifier = uuid;
    // 圖片上傳
    var idf = this.identifier;
    var that = this;
    $('#'+idf+'-tforma').ajaxForm({
        dataType : 'json',
	beforeSubmit : function(a, f, o) {
	  $('#'+idf+'-statusPic').html('上傳中...');
	},
        success : function(data) {	
 	 if (typeof (data) == 'string')
	   data = eval('(' + data + ')');
	 $('#'+idf+'-uploadWindow').window('close');
	 if ("success" == data.message) {
		 $('div[identifier='+that.identifier+']').find('#picPath').val(data.path);
		 $("#"+idf+"-path").val(data.path);
		 $("#"+idf+"-statusPic").html( "<a target='window' href='" + data.path .replace( "\\", "/") + "'>預覽</a>");
	 } else if ("error" == data.message)
		 $("#"+idf+"-statusPic").html("非圖片數據!");
	 else
		 $("#"+idf+"-statusPic").html("上傳數據錯誤!");
		  $("#"+idf+"-itemPic").val('');
	 },
	 error : function(jqXHR, textStatus,errorThrown) {
		 $('#$'+idf+'-uploadWindow').window('close');
		 //console.log("error:"+ data.responseText);
		 //console.log("status:" + textStatus);
		 $("#"+idf+"-statusPic").html("上傳失敗!");
		 $("#"+idf+"-itemPic").val('');
	 } });
	}
/**
	 * <b>商品上傳指定的圖片</b>
	 * 
	 * @param request
	 * @param response
	 * @param command
	 * @return
	 * @throws Exception
	 */
	public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response, SmartMenu command) throws Exception {
		PrintWriter writer = null;
		try {
			response.setContentType("application/json; charset=GBK");
			writer = response.getWriter(); 

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String source = request.getSession().getServletContext().getRealPath("/");
			// 獲得第1張圖片(根據前臺的name名稱得到上傳的文件)
			MultipartFile imgFile1 = multipartRequest.getFile("itemPic");
			// 判斷是否是重複上傳圖片(如果重複將刪除舊圖片)
			String sourceImg = request.getParameter("path");
			if (imgFile1.getContentType().split("/")[0].equals("image")) {
				if (null != sourceImg && !"".equals(sourceImg)) {
					System.out.println("舊圖片路徑:" + sourceImg);
					File f = new File(source + sourceImg);
					if (f.isFile()) {
						f.delete();
						System.out.println(" 刪除成功");
					} else
						System.out.println(" 刪除失敗!");
				}
				String path = null;
				if (imgFile1 != null && imgFile1.getSize() > 0) {
					path = this.getSmartMenuService().storeFile(request.getSession(), imgFile1);
				}
				writer.print("{\"message\":\"success\",\"path\":\"" + path.replace("\\", "\\\\") + "\"}");
			} else
				writer.print("{\"message\":\"error\"}");
		} catch (Exception e) {
			// TODO: handle exception
			writer.print("{\"message\":\"no\"}");
		}
		writer.flush();
		writer.close();
		return null; 
	}


	@Override
	public String storeFile(HttpSession session, MultipartFile file) throws Exception {
		// TODO Auto-generated method stub
		String fileType = file.getContentType().split("/")[1];
		String path = session.getServletContext().getRealPath("/");
		String separator = File.separator;
		String uuid = UUID.randomUUID().toString();
		FileOutputStream fos = null;
		String fileName = null;
		try {
			InputStream fis = file.getInputStream();
			// 轉換文件爲png格式,並保存在同名目錄下
			File files = new File(path + "\\dishpic");
			// 判斷文件夾是否存在,如果不存在則創建文件夾
			if (!files.exists()) {
				files.mkdir();
			}
			if (file.getContentType().split("/")[0].equals("image")) {
				if (path.endsWith(separator))
					fileName = path + "dishpic" + separator + uuid + ".png";
				else
					fileName = path + separator + "dishpic" + separator + uuid + ".png";
				fos = new FileOutputStream(fileName);
				ImageUtil.convertFormat(fis, fos, fileType, "png", 0, 0);
				fos.flush();
				fos.close();
			}
		} catch (Exception ex) {
			System.out.println("文件取出失敗,錯誤信息: " + ex.getMessage());
			if (fos != null)
				fos.close();
			throw ex;
		}
		return "dishpic" + separator + uuid + ".png";
	}
	





/**
 * <b>1.對圖片時行格式轉換</b><br/>
 * <b>2.對圖片進行適度的大小裁剪</b>
 * 
 */
public class ImageUtil {

	/**
	 * 
	 * @param infile 輸入文件
	 * @param outfile 輸出文件
	 * @param srcFormat 源格式
	 * @param destFormat 輸出格式
	 * @return
	 * @throws Exception
	 */
	public static boolean convertFormat(InputStream infile,
			OutputStream outfile, String srcFormat, String destFormat, int width ,int height) throws Exception {
		boolean flag = false;
		BufferedImage src = ImageIO.read(infile);
		if(height > 0  && width > 0) {// compress the origin image if width and height are non-zero
			height = src.getHeight() > height ? height: src.getHeight();
			width = src.getWidth() > width ? width : src.getWidth();
			Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);//這個是用來進行圖片大小調整的
	
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
	
			Graphics g = tag.getGraphics();
			//可在下面對圖片進行繪製和更改
			g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
	
			g.dispose();
			tag.flush();
			flag = ImageIO.write(tag, destFormat, outfile);// 輸出到經過縮放的文件流
		} else {
			flag = ImageIO.write(src, destFormat, outfile);//輸出原分辨率的圖片
		}
		Logger.getLogger(ImageUtil.class).info("圖片轉換成功: 從[" + srcFormat + "]到[" + destFormat + "]");
		return flag;
	}
}

<!-- xml中要配置這段代碼 -- >

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize">
			<value>2048576</value>
		</property>
	</bean>


該代碼是經測試使用的源碼,但是還存在問題!我直接截的圖片能夠上傳,修改過的圖片不能上傳,會報錯

BufferedImage src = ImageIO.read(infile);
ImageIO讀jpg的時候出現javax.imageio.IIOException: Unsupported Image Type  !



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章