基于jquery.uploadify实现图片上传

本文介绍了一种在JSP页面中实现图片上传的方法,详细解释了如何通过自定义的JavaScript工具类进行图片的选择、预览及上传,并对接口调用流程进行了说明。

效果图:


调用说明

1、JSP页面HTML标签,如下添加




2、需要在jsp页面,添加脚本,调用API接口如下:

            var uploadifyItems = [
	        {render:'#uploadify1',fileQueue:'fileQueue1',modelType:'1',imgTarget:'#portraitImg',inputTarget:'#portraitUrl',imgMaxWidth:295,imgMaxHeight:295,newFile:"portraitImg"+Util.getDateTime(6)+Util.UUID(32,16)},
	        {render:'#uploadify2',fileQueue:'fileQueue2',modelType:'9',imgTarget:'#idCardImgView',inputTarget:'#idCardImg',newFile:"idCardImg"+Util.getDateTime(6)+Util.UUID(32,16)},
	        {render:'#uploadify3',fileQueue:'fileQueue3',modelType:'9',imgTarget:'#duplicateIdentityImg',inputTarget:'#duplicateIdentityUrl',newFile:"duplicateIdentityUrl"+Util.getDateTime(6)+Util.UUID(32,16)},
	        {render:'#uploadify4',fileQueue:'fileQueue4',modelType:'9',imgTarget:'#holdIdentityImg',inputTarget:'#holdIdentityUrl',newFile:"holdIdentityUrl"+Util.getDateTime(6)+Util.UUID(32,16)},
	        {render:'#uploadify5',fileQueue:'fileQueue5',modelType:'4',imgTarget:'#licenseImg',inputTarget:'#licenseUrl',newFile:"licenseUrl"+Util.getDateTime(6)+Util.UUID(32,16)},
	        {render:'#uploadify6',fileQueue:'fileQueue6',modelType:'4',imgTarget:'#licenseCopyImg',inputTarget:'#licenseCopyUrl',newFile:"licenseCopyUrl"+Util.getDateTime(6)+Util.UUID(32,16)}
	    ];
	    UploadifyUtils.image.config({
	    	ftpServer:FTP_SERVER
	    });
	    UploadifyUtils.image.init(uploadifyItems);



上述参数说明:

参数
说明
UploadifyUtils.image.config
json,具体详见默认参数。其中ftpServer为图片上传的ftp地址
UploadifyUtils.image.init

json数组,其中:

render:上传控件绑定的div元素,参数值为#id。

fileQueue:上传进度条,绑定的div元素,参数值为#id

modelType:图片上传的ftp目录,即ftpUploadPathConfig.properties配置文件中的参数值。

imgTarget:图片上传成功后绑定显示的img元素。

inputTarget:图片上传成功后绑定的input元素,提交表单使用。

imgMaxWidth:图片尺寸最大宽度,-1为不控制大小。

imgMaxHeight:图片尺寸最大高度,-1为不控制大小。

imgMaxSize:图片上传大小 如: 最大1MB,则值取(1*1024*1024)。

newFile:自定义上传图片名称,Y:使用原上传图片名称


 

源码:

/**
 * 基于jqueryUploadify插件实现图片上传的工具类
 * @author 石冬冬
 * @date 2017/1/18
 */
var UploadifyUtils = {
	/**
	 * 上传图片
	 */
	image:{
		/**
		 * 默认配置项
		 */
		settings:{
			'ftpServer'			:	'',
			'swf'				:	CAR_PATH + '/static/controls/jquery.uploadify-v3.1/uploadify.swf',
			'uploader'        	: 	CAR_PATH + "/imageUpload/upload.do_?temp="+Math.random(),
	        'queueID'        	: 	'fileQueue',
			'fileTypeDesc'		:	'支持格式:jpg/gif/jpeg/png/bmp.',
	        'fileTypeExts'		:	'*.jpg;*.gif;*.jpeg;*.png',
	        'formData'			:	null,
	        'auto'           	:	true,
	        'multi'          	:	false,
	        'uploadLimit' 	 	:	99,
	        'queueSizeLimit'    :	99,
	        'fileSizeLimit'  	:	2*1024*1024,
	        'fileObjName' 	 	: 	'imgFile',
	        'buttonText'     	:	'选择图片',
	        'removeCompleted'	:	true,
	        'removeTimeout'		:	3,
	        'modelType'			:	11,
		    'imgMaxSize'		:	1024*1024,//默认图片1MB
		    'onUploadSuccess'	: 	function(file,data,response) {
			 },
			 'onUploadError' 	: 	function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {
				 layer.msg('上传失败:'+errorMsg, {icon: 2});
			 }
		},
		/**
		 * 对外配置入口
		 * @param options
		 */
		config:function(options){
			$.extend(this.settings,options);
		},
		/**
		 * 初始化插件
		 * @param items
		 */
		init:function(items){
			var settings = this.settings;
			var ftpServer  = settings.ftpServer;
			for(var i in items){
				var $formData = {
					'type'			:	'image',
					'modelType'		:	11,
					'imgMaxWidth'	:	-1,
					'imgMaxHeight'	:	-1,
					'imgMaxSize'	:	settings.imgMaxSize,
					'imgTarget'		: 	null,					//上传成功回调绑定的img元素,如:#identityCardImg
					'inputTarget'	:	null,					//上传成功回调绑定的input元素,一般为hidden类型,如:#identityCardUrl
					'imageIndex'	:	0,						//上传图片索引	
					'newFile'		:	'Y'						//系统自动生成文件名称
				};
				var render = items[i].render;				//上传控件绑定的div元素,参数值为#id。
				var modelType = items[i].modelType;			//图片上传的ftp目录,即ftpUploadPathConfig.properties配置文件中的参数值。
				var imgTarget = items[i].imgTarget;			//图片上传成功后绑定显示的img元素。
				var inputTarget = items[i].inputTarget;		//图片上传成功后绑定的input元素,提交表单使用。
				var imgMaxWidth = items[i].imgMaxWidth;		//图片尺寸最大宽度,-1为不控制大小。
				var imgMaxHeight = items[i].imgMaxHeight;	//图片尺寸最大高度,-1为不控制大小。
				var imgMaxSize = items[i].imgMaxSize;		//图片大小
				var newFile = items[i].newFile;
				settings.queueID = items[i].queueID;
				$.extend($formData,{
					'modelType'		:	modelType,
					'imgMaxWidth'	:	imgMaxWidth,
					'imgMaxHeight'	:	imgMaxHeight,
					'imgMaxSize'	:	imgMaxSize,
					'imgTarget'		: 	imgTarget,			//上传成功回调绑定的img元素,如:#identityCardImg
					'inputTarget'	:	inputTarget,		//上传成功回调绑定的input元素,一般为hidden类型,如:#identityCardUrl
					'imageIndex'	:	i,					//上传图片索引
					'newFile'		:   newFile
				});
				settings.formData = $formData;
				/**
				 * 上传成功的回调函数
				 */
				settings.onUploadSuccess = function(file, data, response){
					data = $.parseJSON(data);
					var error = data.error;
					var message = data.message;
					var imageUrl = data.url;
					if(error==1){
						layer.msg(message, {icon: 2});
					}else{
						imageUrl = imageUrl.replace(ftpServer,'');
						if(imageUrl){
							$(data.imgTarget).attr('src',data.url);
							$(data.inputTarget).val(imageUrl);
							if(data.imageIndex){
								var imageIndex = data.imageIndex;
								$('div.ui-artZoom-box').eq(imageIndex).find('img').attr('src',data.url);//兼容图片重新上传后,放大图片导致还是原先图片现象。
							}
						}
					}
				};
				$(render).uploadify(settings);
			}
		}
	}
};



SpringMVC 后台java处理FTP上传源码:


package com.ucar.base.upload.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ucar.base.upload.utils.UploadConfigUtils;
import com.ucar.base.upload.utils.UploadConfigUtils.ResourceType;
import com.ucar.util.StringTools;
import com.zuche.framework.remote.RemoteClientFactory;
import com.zuche.framework.remote.RemoteType;
import com.zuche.framework.upload.ResourceUploadResultVO;
import com.zuche.framework.upload.ResourceUploadScaleVO;
import com.zuche.framework.upload.ResourceUploadVO;
import com.zuche.framework.utils.FtpUtil;
import com.zuche.framework.utils.PropertiesReader;

/**
 * 图片上传,基于jqueryUploadify 处理
 * @author 石冬冬-Heil Hilter(dd.shi02@zuche.com)
 * @date 2017-1-18 下午4:41:06
 */
@Controller
@RequestMapping("/imageUpload")
public class ImageUploadController{
	private static Logger LOGGER = LoggerFactory.getLogger(ImageUploadController.class);
	private static String[] FILE_TYPES = {"gif","jpg","jpeg","png","bmp"}; 
	private static final String FTP_SERVER = UploadConfigUtils.getFtpServer();
	private static final Properties ftpPathConfig = PropertiesReader.getProperties("ftpUploadPathConfig");
	/**
	 * Description:图片上传 
	 * @Version1.0 2015-12-24 上午9:40:53 by 石冬冬-Chris Suk(dd.shi02@zuche.com)创建
	 * @param request
	 * @param response
	 */
	@RequestMapping("/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response){
		JSONObject resultJSON = new JSONObject();
		String message = "";
		int error = 0;
		String imageUrl = "";
		String fileName = null,fileType=null,modelType=null;//上传图片名称,文件类型
		String imgTarget = null,inputTarget=null;
		String imageIndex = null;
		String cloud = null;//是否启动cloud存储
		boolean verify = true;
		ByteArrayInputStream in = null;
		String newFile = "N";//是否系统生成文件名{Y:系统生成 N:原文件,自定义名称}
        try {
        	response.setContentType("text/html;charset=UTF-8");
	    	if (!(request instanceof MultipartHttpServletRequest)) {
	    		verify = false;
	        	error=1;
	    		message = "无法获取上传的文件!";
	        }
	    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String,Object> uploadParams = multipartRequest.getParameterMap();
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String imgMaxSize = getUploadParam(uploadParams,"imgMaxSize");
            newFile =  getUploadParam(uploadParams,"newFile");
            modelType = getUploadParam(uploadParams,"modelType");
            imgTarget = getUploadParam(uploadParams,"imgTarget");
            inputTarget = getUploadParam(uploadParams,"inputTarget");
            imageIndex  = getUploadParam(uploadParams,"imageIndex");
            cloud = getUploadParam(uploadParams,"cloud");
            
            CommonsMultipartFile item = (CommonsMultipartFile) fileMap.get("imgFile");
            long imgSize = item.getSize();
            in = new ByteArrayInputStream(item.getBytes());
	        FileItem fileItem = item.getFileItem();
	        fileName = fileItem.getName();
	        fileType = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
	        if(!Arrays.asList(FILE_TYPES).contains(fileType)){
	        	verify = false;
	        	error=1;
	        	message = "图片只支持gif,jpg,jpeg,png,bmp文件类型";
	        }
	        if(StringTools.isNotEmpty(imgMaxSize) && imgSize>Long.valueOf(imgMaxSize)){
	        	verify = false;
	        	error=1;
	        	message = String.format("图片大小不能大于%s", formateImageSize(Long.valueOf(imgSize)));
	        }
	        if(verify){
	        	FtpUtil ftpUtil = FtpUtil.getInstance();
	        	ftpUtil.connectServer();
	        	String modelTypePath = ftpPathConfig.getProperty(modelType);
	        	String uploadPath = modelTypePath + (modelTypePath.endsWith("/") ? "" : "/" )  + getFtpRemoteFileDir();
	        	String ftpUploadPath = uploadPath;
	        	String chkMsg = verifyImg(uploadParams, in);
        		if(StringUtils.isNotEmpty(chkMsg)){
        			message = chkMsg;
        			error=1;
        			verify = false;
        		}else{
        			in.reset();
        			String ftpFileName = UUID.randomUUID().toString()+"."+fileType;
        			if(StringTools.isNotEmpty(newFile) && !"Y".equals(newFile) && !"N".equals(newFile)){
        				ftpFileName = newFile + "." + fileType;
        			}else{
        				if("Y".equals(newFile)){
            				ftpFileName = fileName;
            			}
        			}
        			boolean flag = ftpUtil.upload(ftpUploadPath, ftpFileName, in);
        			if (!flag) {
        				error=1;
        				message = "图片上传失败";
        				verify = false;
        			}
        			
        			if(StringTools.isEmpty(cloud) || Boolean.valueOf(cloud)){
        				//同步写入Hbase
        				/*********************************************/
        				ResourceUploadVO vo = new ResourceUploadVO();
        				vo.setName(uploadPath + ftpFileName);
        				vo.appendImageType(UploadConfigUtils.getCloudUploadModel());
        				vo.setData(item.getBytes());
        				vo.setCompress(true);
        				vo.setCompressSize(10); 
        				List<ResourceUploadScaleVO> list = new ArrayList<ResourceUploadScaleVO>();
        				ResourceUploadScaleVO scaleVO = new ResourceUploadScaleVO("small", 500, 500,null,true);
        				list.add(scaleVO);
        				vo.setScaleInfos(list);
        				final String SERVICE_NAME = "carresources.commonResourceInsert.service";
        				ResourceUploadResultVO resultVO = (ResourceUploadResultVO) RemoteClientFactory.getInstance(RemoteType.HESSIAN).executeToObject(SERVICE_NAME, vo);
        				String cloudServer = UploadConfigUtils.getCloudServer();
        				LOGGER.error("cloudServer={},resourceUploadResultVO={}",cloudServer,JSON.toJSON(resultVO));
        				//LOGGER.error("uploadOrigPath={},uploadCompressPath={}",cloudServer+resultVO.getOriginalName(),cloudServer+resultVO.get);
        				/*********************************************/
        				imageUrl = UploadConfigUtils.getCloudPath(ResourceType.IMAGE) + uploadPath + ftpFileName;
        			}else{
        				imageUrl = FTP_SERVER + uploadPath + ftpFileName;
        			}
        		}
	        	if(verify){
	        		message = "图片上传成功";
	        		error=0;
	        	}
	        	ftpUtil.closeConnect();
	        }
        }catch (Exception e) {
        	error=1;
        	message = "上传文件失败:"+e.getLocalizedMessage();
            LOGGER.error(e.getMessage(), e);
        }finally{
        	try {
				if(null!=in){in.close();}
			} catch (IOException e) {
				error=1;
				message = "ByteArrayInputStream释放异常:"+e.getLocalizedMessage();
				LOGGER.error("ByteArrayInputStream释放异常:", e);
			}
        }
        resultJSON.put("error", String.valueOf(error));
        resultJSON.put("message", message);
        resultJSON.put("url", imageUrl);
        resultJSON.put("fileName", fileName);
        resultJSON.put("fileType", fileType);
        resultJSON.put("imgTarget", imgTarget);
        resultJSON.put("inputTarget", inputTarget);
        resultJSON.put("imageIndex", imageIndex);
        try {
        	LOGGER.error(resultJSON.toJSONString());
			response.getWriter().print(resultJSON.toJSONString());
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
	/**
	 * Description: 获取图片上传目录
	 * @Version1.0 2015-12-22 上午10:58:35 by 石冬冬-Chris Suk(dd.shi02@zuche.com)创建
	 * @return
	 */
	private static String getFtpRemoteFileDir() {
		StringBuilder remoteFileDir = new StringBuilder();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String datePath = sf.format(new Date());
		remoteFileDir.append(datePath).append("/");
		return remoteFileDir.toString();
	}
	/**
	 * Description:获取上传参数 
	 * @Version1.0 2016-5-5 下午1:25:42 by 石冬冬-Chris Suk(dd.shi02@zuche.com)创建
	 * @param uploadParams
	 * @param key 参数
	 * @return
	 */
	private static String getUploadParam(Map<String,Object> uploadParams,String key){
		Object obj = uploadParams.get(key);
		if(null!=obj){
			String[] objArray = (String[])obj;
			return objArray[0];
		}
		return null;
	}
	/**
	 * Description:图片校验 
	 * @Version1.0 2015-12-22 下午5:32:04 by 石冬冬-Chris Suk(dd.shi02@zuche.com)创建
	 * @param uploadParams
	 * @param in
	 * @return
	 */
	private static String verifyImg(Map<String, Object> uploadParams,InputStream in){
		String message = null;
		try {
			String imgMaxWidth = getUploadParam(uploadParams,"imgMaxWidth");
			String imgMaxHeight = getUploadParam(uploadParams,"imgMaxHeight");
			if(null!=imgMaxWidth && null!=imgMaxHeight){
				int maxWidth = Integer.parseInt(imgMaxWidth);
				int maxHeight = Integer.parseInt(imgMaxHeight);
				if(maxWidth==-1||maxHeight==-1){
					message = null;
				}else{
					BufferedImage img = ImageIO.read(in);
					int width = img.getWidth();
					int height = img.getHeight();
					if(width>maxWidth||height>maxHeight){
						message = String.format("图片尺寸不符合,尺寸最大为%s×%s", imgMaxWidth,imgMaxHeight);
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("【图片导入】图片校验处理异常", e);
		}
		return message;
	}
	
	private static String formateImageSize(long imgMaxSize){
		String formate = String.format("%sK", imgMaxSize);
		final long K = 1024 * 1024,MB = 1024 * K;
		if(imgMaxSize>K){
			formate = String.format("%sMB", imgMaxSize/K);
		}
		if(imgMaxSize>MB){
			formate = String.format("%sG", imgMaxSize/MB);
		}
		return formate;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值