1. 程式人生 > >java專案例項圖片上傳

java專案例項圖片上傳

一、上傳對錶單的要求

1) 表單的提交方式 :"method=post"

2) 表單的型別 :enctype="multipart/form-data"

3) 上傳表單的檔案項:<input type="file" name="xx" /> //其中名字是必須要的


二.上傳的一般步驟

1.將request轉化為MultipartHttpServletRequest multipartRequest= (MultipartHttpServletRequest)(request);

原理是:使用spring的CommosMultipartResolver 配置MultipartResolver 用於檔案上傳,

DispatcherServlet 將呼叫 MultipartResolver 的 isMultipart(request) 方法檢查當前 Web 請求是否為 multipart型別。如果是,DispatcherServlet 將呼叫 MultipartResolver 的 resolveMultipart(request) 方法,對原始 request 進行裝飾,並返回一個 MultipartHttpServletRequest 供後繼處理流程使用(最初的 HttpServletRequest 被偷樑換柱成了 MultipartHttpServletRequest),否則,直接返回最初的 HttpServletRequest。

獲取檔案

         MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request; //將request轉化為MultipartHttpServletRequest

 MultipartFile multipartFile = multipartRequest.getFile("upload");//獲取檔案

         InputStream is = multipartFile.getInputStream();//獲取圖片的檔案流
        String uploadContentType = multipartFile.getOriginalFilename();//獲取檔案的格式

2.判斷檔案的格式(必須為.jpg/.gif/.bmp/.png檔案)) 3.對圖片進行處理(壓縮圖片),並輸出到指定目錄 4.在資料庫中儲存圖片的路徑名imgDir+imgName

jsp頁面程式碼

<%@ page language="java" pageEncoding="UTF-8"%>
<%@include file="/include.jsp"%>
<%@page import="java.util.Date"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link href="<ph:root/>/s/css/style.css" type="text/css" rel="stylesheet" />
<link href="<ph:root/>/s/css/gh-buttons.css" type="text/css"
	rel="stylesheet" />
<link href="<ph:root/>/s/css/selectinput.css" type="text/css"
	rel="stylesheet" />
<link href="<ph:root/>/s/js/ueditor/themes/default/css/ueditor.css"
	type="text/css" rel="stylesheet" />
<script type="text/javascript" src="<ph:root/>/s/js/jquery.min.js"></script>
<script type="text/javascript" src="<ph:root/>/s/js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="<ph:root/>/s/js/jquery.form.js"></script>
<script type="text/javascript" src="<ph:root/>/s/js/common.js"></script>
<script type="text/javascript" src="<ph:root/>/s/js/checkForm.js"></script>

<script type="text/javascript">
	$(document).ready(function() {
		//$("textarea[name='content']").ckeditor();
		var uEditor = UE.getEditor("content1", {
			initialFrameWidth : 800,
			initialFrameHeight : 400,
			autoHeightEnabled : false,
			contextMenu : []
		});
		/* uEditor.onblur = function(){
			if(uEditor.getContent()){
				uEditor.commands.autotypeset.execCommand();
			}
		} */

	});

	function tolist() {
		window.location.href = "<ph:root/>/m/periodicals/list";
	}

	function submitForm() {
		if (!checkForm("form1")) {
			return false;
		}
		if (confirm("確認儲存?")) {
			openLoad("正在處理,請稍後。。。");
			//防止重複提交
			$("#submit_btn").attr("disabled", true);
			$("#form1").ajaxSubmit({
				url : '<ph:root/>/m/periodicals/addContentDo',
				type : 'post',
				dataType : 'json',
				success : function(result) {
					closeLoad();
					$("#submit_btn").attr("disabled", false);
					if (result.resultCode == 0) {
						alert("提交成功");
						tolist();
						return true;
					} else {
						alert(result.resultMsg);
						return false;
					}
				}
			});
		}
	}
	
	function showPreviewImg(){
		$("#imgTr").show();
	}
	
	//圖片預覽
	function setImagePreview(id,oldId,localImageId) {
	    var docObj=document.getElementById(id);
	    var imgObjPreview=document.getElementById(oldId);
	    var allowExtention = ".jpg,.bmp,.gif,.png";
	    $("#"+oldId).show();
	    var extention = docObj.value.substring(docObj.value.lastIndexOf(".") + 1).toLowerCase(); //獲取當前上傳檔案的副檔名
	    if(allowExtention.indexOf(extention) == -1){
	    	alert("請選擇.jpg,.bmp,.gif,.png檔案");
	    	return false;
	    } 


	    if(docObj.files && docObj.files[0]){
	    	if (window.FileReader) {
	        	var reader = new FileReader();
	            reader.onload = function(e) {
	                document.getElementById(oldId).setAttribute("src", e.target.result);
	            }
	            reader.readAsDataURL(docObj.files[0]);
	        } else if (browserVersion.indexOf("SAFARI") > -1) {
	            alert("不支援Safari瀏覽器6.0以下版本的圖片預覽!");
	        } else {
	            alert("不支援您當前使用的瀏覽器的圖片預覽!");
	        }
	    }else{
	        //IE下,使用濾鏡
	        docObj.select();
	        window.parent.document.body.focus();
	        var imgSrc = document.selection.createRange().text;
	        var localImagId = document.getElementById(localImageId);
	        //必須設定初始大小
	        localImagId.style.width = "100px";
	        localImagId.style.height = "100px";
	        //圖片異常的捕捉,防止使用者修改後綴來偽造圖片
			try{
	            localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
	            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
	        }catch(e){
	            alert("您上傳的圖片格式不正確,請重新選擇!");
	            return false;
	        }
	       imgObjPreview.style.display = 'none';
	       //$("#"+oldId).hide();
	        document.selection.empty();
	        
	    }
	    return true;
	}
</script>
</head>
<body>
	<jsp:include page="../head.jsp"></jsp:include>
	<div id="content">
		<jsp:include page="../left.jsp"></jsp:include>
		<div class="right">
			<div class="titlebar">
				<span>當前功能:<a href="#"></a>期刊章節管理  >  <b>新增電子院報章節</b>
				</span>
				<div class="user-1"></div>
			</div>
			<div class="frame" id="frame">
				<div class="guntx_z">
					<div class="guntx_z1">
						<div id="bj3">
							<sf:form modelAttribute="periodicalsChapter" action="addDo"
								method="post" id="form1" name="form1"
								enctype="multipart/form-data">
								<input type="hidden" name="parentId" checkItems="N" value="${id}" />
								<%-- 1 圖文新聞 --%>
								<div>
									<div class="titlebar1">
										<div class="tab_font1">
											<span style="margin-left: 30px; color: red">帶 *
												號為必填項</span>
										</div>
									</div>

									<div class="titlebar2">
											<table width="97%" style="border:1px solid #ccc">
												<tr>
												  
													<td width="20%" align="right" bgcolor="#ffffff"><span
														class="fontts"> * </span>標題:</td>
													<td width="80%" align="left" bgcolor="#FFFFFF"
														style="padding-left: 20px;"><sf:input path="title"
															checkItems="N" style="width:300px;height:30px;"
															maxlength="50" placeholder="請輸入期刊名" /></td>
												</tr>
												<tr>
							         <td align="right" bgcolor="#ffffff">封面圖片:</td>
							       <td bgcolor="#FFFFFF" style="vertical-align: top;padding-left: 20px;">
								     <input id="upload" name="upload" type="file" style="width:367px;height:30px;" onchange="showPreviewImg();setImagePreview('upload','imgView','divNewPreview')"/> 
								   <span class="fonttsDef" id="thumbUrlRightId" style="text-align: right"> 
									尺寸:520*320 px 檔案大小:100KB以內,檔案格式:jpg,jpeg,gif,bmp,png 
								   </span>
							     </td>

						        </tr>
						          <%-- <c:if test="${upload!=null}"></c:if> --%>
						        <tr style="display:none" id="imgTr">
							    <td align="right" bgcolor="#ffffff">圖片預覽</td>
							      <td bgcolor="#FFFFFF" style="padding-left: 20px;">
								<img id="imgView" src=''  alt=""  style="display:none" width="150" height="100"/>
								<div id="divNewPreview"></div>
							     </td>
						         </tr>
												<tr>
													<td align="right" bgcolor="#ffffff"><span
														class="fontts"> * </span>內容:</td>
													<td align="left" bgcolor="#FFFFFF"
														style="padding-left: 20px;"><sf:textarea
															path="content" id="content1" /></td>
												</tr>
											</table>
										
									</div>
								</div>
								<div class="baocun button-group minor-group">
									<input type="button" onclick="return submitForm()"
										id="submit_btn" name="subButton" class="buttonqr" value="儲存" />
									<input type="button" onclick="tolist()" name="subButton"
										class="buttonqr_cancel" value="取消" />
								</div>
							</sf:form>
						</div>
					</div>
				</div>
			</div>
			<!--釋出內容程式碼結束-->

		</div>
	</div>
	<jsp:include page="../foot.jsp"></jsp:include>
	<script type="text/javascript" charset="utf-8"
		src="<ph:root/>/s/js/ueditor/ueditor.config.js"></script>
	<script type="text/javascript" charset="utf-8"
		src="<ph:root/>/s/js/ueditor/ueditor.all.js"></script>
	<script type="text/javascript" charset="utf-8"
		src="<ph:root/>/s/js/ueditor/lang/zh-cn/zh-cn.js"></script>
</body>
</html>

java 後臺程式碼

controller
@Autowired
private Executor threadPoolTaskExecutor;
/**
		    *後臺新增電子院報章節內容
		    * 
		    * 
		    */
		@RequestMapping(value = "/m/periodicals/addContentDo")
		public void addContentDo(@ModelAttribute PeriodicalsChapter periodicalsChapter,Model model,HttpServletRequest request,HttpServletResponse response){
			Map<String,Object> map = new HashMap<String,Object>();
			InputStream is = null;
			Gson gson = new Gson();
			try{
				MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;  
				MultipartFile multipartFile = multipartRequest.getFile("upload");
				String uploadContentType = multipartFile.getOriginalFilename();
				if(multipartFile != null && multipartFile.getSize() != 0){
					String expandedName = CommonUtil.checkImg(uploadContentType);
					if(expandedName.equals("")){
						map.put("resultCode", 3);
						map.put("resultMsg", "檔案格式不正確(必須為.jpg/.gif/.bmp/.png檔案)!");
						String jsonStr = gson.toJson(map);
						AjaxUtil.ajaxHtml(jsonStr, response);
						return ;
					}
					String imgName = System.currentTimeMillis() + "_" + ((int) (Math.random() * 900) + 100) + "." + expandedName;
					is = multipartFile.getInputStream();
					threadPoolTaskExecutor.execute(
							new ImageCompressionTask(is, imgName, 520, 320)
					);
					periodicalsChapter.setTopThumbUrl(CommonUtil.getFolder(imgName));
				}//壓縮圖片				
				periodicalsChapter.setCreateTime(new Date().getTime());//獲取時間
				periodicalsChapter.setTitle(periodicalsChapter.getTitle());
				periodicalsChapter.setContent(periodicalsChapter.getContent());
				periodicalsChapter.setParentId(periodicalsChapter.getParentId());
				//儲存
			if(periodicalsChapterService.addPeriodicalsChapter(periodicalsChapter)){					
				map.put("resultCode", 0);
				map.put("resultMsg", "釋出成功");
				String jsonStr = gson.toJson(map);
				AjaxUtil.ajaxHtml(jsonStr, response);
				return ;
			}else{
				map.put("resultCode", 1);
				map.put("resultMsg", "釋出失敗");
				String jsonStr = gson.toJson(map);
				AjaxUtil.ajaxHtml(jsonStr, response);
			}
			}catch(Exception e){
				logger.error("儲存異常",e);
				map.put("resultCode", 1);
				map.put("resultMsg", "釋出失敗");
				String jsonStr = gson.toJson(map);
				AjaxUtil.ajaxHtml(jsonStr, response);
			}
		} 


1.CommonUti類的checkImg的方法,檢查檔案的格式
package com.rmyy.web.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.rmyy.web.model.Channel;
import com.rmyy.web.util.DateUtil;
import com.rmyy.web.util.PropertyFileUtil;

public class CommonUtil {
	public static   String getFolder(String imgName) {
		// 圖片上下文
		String imgContext = PropertyFileUtil.get("imgContext");
		String dateStr = DateUtil.getDate();
		String imgDir = imgContext + "/" + dateStr + "/";
		return imgDir+imgName;
	}
	
	public static String  checkImg(String uploadContentType){
		String expandedName = "";
		if (uploadContentType.endsWith(".jpg") || uploadContentType.endsWith(".JPG")) {
			// IE6上傳jpg圖片的headimageContentType是image/pjpeg,而IE9以及火狐上傳的jpg圖片是image/jpeg
			expandedName = "jpg";
		} else if (uploadContentType.endsWith(".png") || uploadContentType.endsWith(".PNG")) {
			// IE6上傳的png圖片的headimageContentType是"image/x-png"
			expandedName = "png";
		} else if (uploadContentType.endsWith(".gif")) {
			expandedName = "gif";
		} else if (uploadContentType.endsWith(".bmp")) {
			expandedName = "bmp";
		}
		return expandedName;
	}
	
	
	 // 校驗檔案尺寸跟大小
		public static String checkFileImg(MultipartFile file,String photoSizeStr,String photoWidthStr,String photoHeightStr) throws IOException {
			int photoSize = photoSizeStr!=null?Integer.parseInt(photoSizeStr):0;
        	int photoWidth = photoWidthStr!=null?Integer.parseInt(photoWidthStr):0;
        	int photoHeight = photoHeightStr!=null?Integer.parseInt(photoHeightStr):0;
			CommonsMultipartFile cf= (CommonsMultipartFile)file;
			String result = "";
			String tip = "請上傳圖片尺寸為"+photoWidth+"*"+photoHeight+"!";
			BufferedImage image =ImageIO.read(cf.getInputStream());
			//BufferedImage image = ImageIO.read(f);
			if (file.getSize() > photoSize * 1024) {
				result = "檔案大小不得大於" + photoSize + "kb!";
				return result;
			}
			if (image.getWidth() < (photoWidth) || image.getWidth() > (photoWidth + 20)) {
				return tip;
			}
			
			if (image.getHeight() < (photoHeight) || image.getHeight() > (photoHeight + 20)) {
				return tip;
			}
			
			return null;
		}
		
	
}
2.圖片壓縮
package com.rmyy.web.common.task;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.rmyy.web.common.CommonUtil;
import com.rmyy.web.util.DateUtil;
import com.rmyy.web.util.ImageUtils;
import com.rmyy.web.util.PropertyFileUtil;

public class ImageCompressionTask implements Runnable{

	protected static Logger logger = Logger.getLogger(ImageCompressionTask.class);
	private InputStream is;
	private int width;
	private int height;
	private String fileName;
	
	/**
	 * 初始化引數
	 * @param file  圖片
	 * @param id    ID
	 * @param type  圖片分類1為商家管理圖片2為產品分類圖片
	 * @param fileName  圖片名稱
	 * @param width   高
	 * @param height  寬
	 */
	public ImageCompressionTask(InputStream is,String fileName,int width,int height){
		this.is = is;
		this.width = width;
		this.height = height;
		this.fileName = fileName;
	}
	
	
	public void run() {
		try{
			this.compressPic();
		}catch(Exception e){
			logger.error("生成壓縮圖失敗! " ,e);
		} 
	}
	
	
	/**
	 * 圖片壓縮
	 * @return
	 */
	private String compressPic() throws Exception {
		String rootPath = PropertyFileUtil.get("imgPath");
		String path = getFolder(rootPath); //根路徑下的子目錄
		String urlPath =  path + fileName;
		
		BufferedImage buffImg;
		FileOutputStream output = null;
		try {
			String extentionName = "";
			if(fileName.lastIndexOf(".") != -1){
				extentionName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			}
			
			extentionName = extentionName.toLowerCase(); //沒有副檔名的url
			
			buffImg = ImageIO.read(is);
			if(buffImg == null){
				return null;
			}
			BufferedImage compressPic = ImageUtils.compressPicMin(buffImg, width, height);//圖片等比縮放
			if(compressPic != null){ //圖片已壓縮
				output = new FileOutputStream(urlPath);
				ImageUtils.write(compressPic, extentionName, output);//圖片輸出
			}
		}finally {
			if(output != null){
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is != null){
				is.close();
			}
		}
		return "";
	}
	
	
	
	//儲存路徑獲取
	private   String getFolder(String rootPath) {
		// 圖片上下文
		String imgContext = PropertyFileUtil.get("imgContext");
		String dateStr = DateUtil.getDate();
		String imgDir = imgContext + "/" + dateStr + "/";
		String path = rootPath + imgDir;
		File dir = new File(path);
		if (!dir.exists()) {
			try {
				dir.mkdirs();
			} catch (Exception e) {
				return "";
			}
		}
		return path;
	}

	


	public int getWidth() {
		return width;
	}


	public void setWidth(int width) {
		this.width = width;
	}


	public int getHeight() {
		return height;
	}


	public void setHeight(int height) {
		this.height = height;
	}


	public static Logger getLogger() {
		return logger;
	}


	public static void setLogger(Logger logger) {
		ImageCompressionTask.logger = logger;
	}
	
	public static void main(String args[]){
		String abc = "abc";
		String ab2 = "abc";
		System.out.print(abc==ab2);
	}
}


3.圖片等比縮放,先要設定寬和高
package com.rmyy.web.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description: 圖片工具類
 *
 * @author KangWei
 * @Date 11-2-23
 */
public class ImageUtils {
	private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
	
	
	/**1111
	 * 將圖片寫入輸出流
	 *
	 * @param image
	 *            BufferedImage 物件
	 * @param format
	 *            輸出格式
	 * @param output
	 *            輸出流
	 * @throws java.io.IOException
	 *             IO異常
	 */
	public static void write(BufferedImage image, String format,
			OutputStream output) throws IOException {
		ImageIO.write(image, format, output);
	}

	

	
	/**111
	 * 圖片等比縮放,先要設定寬和高
	 *
	 * @param image
	 * @param
	 * @throws java.io.IOException
	 */
	public static BufferedImage compressPicMin(BufferedImage image,
			int outputWidth, int outputHeight) throws IOException {
		if (image == null) {
			return null;
		}

		if (image.getWidth(null) < outputWidth
				&& image.getHeight(null) < outputHeight) {
			return image;
		}

		int newWidth;
		int newHeight;
		// 為等比縮放計算輸出的圖片寬度及高度
		double rate1 = ((double) image.getWidth(null)) / (double) outputWidth;
		double rate2 = ((double) image.getHeight(null)) / (double) outputHeight;
		// 根據縮放比率大的進行縮放控制
		double rate = rate1 < rate2 ? rate1 : rate2;
		newWidth = (int) (((double) image.getWidth(null)) / rate);
		newHeight = (int) (((double) image.getHeight(null)) / rate);

		BufferedImage tag = new BufferedImage(newWidth, newHeight,
				BufferedImage.TYPE_INT_RGB);
		/*
		 * Image.SCALE_SMOOTH 的縮略演算法 生成縮圖片的平滑度的 優先順序比速度高 生成的圖片質量比較好 但速度慢
		 */
		tag.getGraphics().drawImage(
				image.getScaledInstance(newWidth, newHeight,
						Image.SCALE_SMOOTH), 0, 0, null);
		return tag;
	}

	
}




4.系統性工具類
package com.rmyy.web.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 系統屬性工具類
 * 
 * @author HenryYan
 */
public class PropertyFileUtil {

	private static Properties config = null;
	private static Logger logger = Logger.getLogger(PropertyFileUtil.class);
	
	static {
		InputStream in = PropertyFileUtil.class.getClassLoader().getResourceAsStream("application.properties");
		config = new Properties();
		try {
			config.load(in);
			in.close();
		} catch (IOException e) {
			logger.error("載入系統引數配置異常========", e);
		}
	}

	/**
	 * 根據key 得到value
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		try {
			String value = config.getProperty(key);
			return value;
		} catch (Exception e) {
			logger.error("系統引數配置錯誤========", e);
			return null;
		}
	}
}