网页图片上传

1.jsp页面
<html>
<head>
<title>图片上传演示</title>

<script type="text/javascript" src="http://common/js/jquery-1.7.2.min.js"></script>
</head>
<body>

<form id="img_form" name="img_form" enctype="multipart/form-data" method="post" target="frameImg" action=""  style="cursor:pointer;">

	<img src="" id="image" name="image">
	<input type="file" name="pic" id="upfile">
	<input id="upload" type="button" οnclick="uploadImg()">
</form>

kkkkkkkkkkkkkkkk
 <div id="shImg" class="shImg"></div>
 kkkkkkkkkkkkk
<iframe id="frameImg" name="frameImg" style="display:none"></iframe>


<script>
 var uploadImg = function(){
 $("#img_form").attr("action","/admin/sns/maitian/ImgUploadAction.do?_action=imageUplo");
 
 	$("#img_form").submit();
 
 };
 
 
  /**
  * 图片上传
 * @param obj
 */
function showImg(obj){
		if(obj != ""){
		
			$("#shImg").html("<img id='picImg' class='picImg' src='http://aa/bb/" + obj + "_w_180_180.jpg' height='120' width='120'/>");
		
		}else{
			alert("您上传的图片格式不正确!");
			
		}
	};
	
</script>

</body>


</html>



2.后台action

package cn.damai.phoenix.controller.admin.sns.maitian;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import Voosay.API.Photos;
import Voosay.API.Base.Result;

import eagle.web.ActionGroupImpl;
import eagle.web.annotation.Param;

public class ImgUploadAction extends ActionGroupImpl{
	
	private Logger logger = Logger.getLogger(ImgUploadAction.class);
	
	
	/**
	 * 图片上传
	 */
	@SuppressWarnings("unchecked")
	public void imageUplo() {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		String path = "";		 
		try {
			List<FileItem> items = sfu
					.parseRequest((HttpServletRequest) this.request
							.getRequest());
			for (int i = 0; i < items.size(); i++) {
				FileItem item = items.get(i);
				if (!item.isFormField()) {
					InputStream stream = item.getInputStream();					
					 ByteArrayOutputStream baos = new ByteArrayOutputStream();
	                    int len = 0;
	                    byte[] b = new byte[1024];
	                    while ((len = stream.read(b, 0, b.length)) != -1) {
	                        baos.write(b, 0, len);
	                    }
	                    byte[] buffer = baos.toByteArray();
	                    MemoryCacheImageInputStream mcis = null;
	                    try {
		                    mcis = new MemoryCacheImageInputStream(new ByteArrayInputStream(buffer));
		                    Iterator<ImageReader> iterator = ImageIO.getImageReaders(mcis);
		                    while (iterator.hasNext()) {
			                    ImageReader reader = (ImageReader) iterator.next();
			                    String imageName = reader.getClass().getSimpleName();
			                    if (!StringUtils.isNullString(imageName) && ("PNGImageReader".equals(imageName))) {			                    						
			    					path = uploadMaitianPic(new ByteArrayInputStream(buffer));	
			    							    					
				                 }
			                    else {
				                    	path="";
									}
			                    }
	                    }catch (Exception e) {
	                    	e.printStackTrace();
	                    } finally {
		                    try {
			                    if (null != mcis) {
			                    mcis.close();
			                    mcis = null;
		                    }
		                    } catch (Exception e) {
		                    	e.printStackTrace();
		                    }
	                    }
					
				}
			}
		
		} catch (Exception e) {
			logger.error(e);
			path = "";
		}
		
		System.out.println(path+"=======");
		response.write("<script>parent.showImg('" + path + "')</script>");
		response.end();
	}
	
	
//	public void imageUplo() {
//		String  fileName = "";
//		try {
//			InputStream  input = request.getFile("img_form").getInputStream();
//		} catch (Exception e) {
//			logger.error(e);
//			response.write("<script>parent.showMaitianLogo('" + fileName +"'"+","+ty+")</script>");
//			response.end();
//		}
//		response.write("<script>parent.showMaitianLogo('" + fileName +"'"+","+ty+")</script>");
//		response.end();
//		
//	}
	
	
	 private String uploadMaitianPic(InputStream input) {
	    	// 当前时间毫秒数为文件名前缀
	    	List<String> listPic = new ArrayList<String>();
	    	listPic.add("w-180*180");
	    	listPic.add("w-150*150");
	    	listPic.add("w-90*90");
	    	listPic.add("w-50*50");

	    	String fileName =createFileName();
	    	String datePath = createMaitianPath();
	    	String filePathName = "aa/bb/"+datePath;
	    	String fullFileName = datePath+"/"+fileName;
	    	try {		
	    		  Photos.upload(null, input,  filePathName, fileName,  listPic, new Result());	
	    		
	    	} catch (Exception e) {
	    		 e.printStackTrace();
	    	}
	    	System.out.println(fullFileName);
	    	return fullFileName;
	    }
	 
	 
	 public static String createFileName(){
			String fileName="";
			Random random=new Random();
			fileName=fileName+System.currentTimeMillis()+random.nextInt(10000)+random.nextInt(10000);
			return fileName;
		}
	 
	 
		/**
		 * 创建上传图片的路径
		 * @param dir 二级目录,比如sns
		 * @return
		 */
		public static String createMaitianPath(){
			StringBuffer sb=new StringBuffer();
			sb.append(DateUtils.parseStringFromDate(DateUtils.getCurrentTime(), "yyyy")).append("/");
			sb.append(DateUtils.parseStringFromDate(DateUtils.getCurrentTime(), "MM"));
			//sb.append(DateUtils.parseStringFromDate(DateUtils.getCurrentTime(), "dd"));
			return sb.toString();
		}

}

Photo.java见Voosay.API


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值