swf文件上传

一。数据库脚本:



文件上传工具类:

package com.sctf.cpm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.log4j.Logger;

public class PhotoUtil {
	public static final Logger log = Logger.getLogger(PhotoUtil.class);
	public static final String PHOTO_CONFIG_PATH = "photo-Config.properties";
	public static final String STORE_DIR_CONFIG = "photo.store_dir";
	public static final String STORE_TYPE_CONFIG = "photo.store_type";
	public static final String MAX_SIZE_CONFIG = "photo.maxSize";
	public static final String FILE_STORE = "2";
	public static final String DATABASE_STORE = "1";

	public static final java.util.Properties PHOTOCONFIG = new java.util.Properties();
	static {

		// java.util.Properties prop = new java.util.Properties();

		org.springframework.core.io.Resource re = new org.springframework.core.io.ClassPathResource(
				PHOTO_CONFIG_PATH);
		java.io.InputStream is = null;
		try {
			is = re.getInputStream();

			PHOTOCONFIG.load(is);

			if (is != null) {
				is.close();
				is = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (Exception e1) {

			}
		}

	}

	public static final String STORE_DIR = PHOTOCONFIG.getProperty(STORE_DIR_CONFIG);
	public static final String STORE_TYPE = PHOTOCONFIG.getProperty(STORE_TYPE_CONFIG);
	public static final long MAX_SIZE = Long.parseLong(PHOTOCONFIG.getProperty(MAX_SIZE_CONFIG));
	public static final File root =  makePhotoRootDIr();
/**
 * 生成存储根目录
 * @Title: makePhotoRootDIr 
 * @throws Exception
 */
	public static File makePhotoRootDIr(){
		File dir = new File(STORE_DIR);
		if (!dir.exists()) {
			if (!dir.mkdirs()) {
				log.error("创建照片根目录失败!");
				return null;
			}
		}else if(!dir.isDirectory() || !dir.canExecute()  || !dir.canWrite()|| !dir.canRead()){
			log.error("照片根目录不是有效的文件夹!");
			return null;
		}
		return dir;
	}
	/**
	 * 生成存储目录層次(年\月\天)
	 * @Title: makePhotoDir 
	 * @return
	 * @throws Exception
	 */
	public static File makePhotoDir()throws Exception{
		if(root == null){
			log.error("照片根目录无效!创建照片目录失败!");
			throw new Exception("照片根目录无效!创建照片目录失败!");
		}
		//create yeardir.
		DateFormat yeardf = new SimpleDateFormat("yyyy");
		DateFormat monthdf = new SimpleDateFormat("MM");
		DateFormat daydf = new SimpleDateFormat("dd");
		String subdirpath = root.getPath()+File.separatorChar+yeardf.format(new Date())+File.separatorChar+monthdf.format(new Date())+File.separatorChar+daydf.format(new Date());
		File daydir = new File(subdirpath);
		if (!daydir.exists()) {
			if (!daydir.mkdirs()) {
				throw new Exception("创建照片目录失败!");
			}
		}else if(!daydir.isDirectory() || !daydir.canExecute()  || !daydir.canWrite()|| !daydir.canRead()){
			throw new Exception("照片目录不是有效的文件夹!");
		}
		return daydir;
	}
/**
 * 存储文件方法
 * @Title: fileStore 
 * @param f
 * @throws Exception
 */
	public synchronized static String fileStore(File f) throws Exception{
		if (f != null && f.canRead()) {
			
			File dir = makePhotoDir();
			Path source = FileSystems.getDefault().getPath(f.getPath());
			Path target = FileSystems.getDefault().getPath(dir.getPath(), makePhotoName());
			Path target2 = Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
			if(target2 != target){
				log.error("移动照片文件失败!");
				throw new Exception("移动照片文件失败!");
			}
			if(target.getNameCount()>=4){
				return target.getName(target.getNameCount()-4)
						+File.separator+target.getName(target.getNameCount()-3)
						+File.separator+target.getName(target.getNameCount()-2)
						+File.separator+target.getName(target.getNameCount()-1);
			}
			/*return dir.getParentFile().getParentFile().getName()
					+ File.separatorChar + dir.getParentFile().getName()
					+ File.separatorChar + dir.getName() + File.separatorChar
					+ target.getName(1);*/
		}
		return null;

	}
	
	public synchronized static String fileStore(InputStream f) throws Exception{
		if (f != null) {
			try{				
				File dir = makePhotoDir();
				File target = new File(dir.getPath(),makePhotoName());
				OutputStream outs = new FileOutputStream(target);
				
				try{
					byte[] b = new byte[1024];
					for(int i=0; (i = f.read(b))!=-1;i = 0)
					{
						outs.write(b, 0, i);
					}
				}catch(IOException e){

					if(f != null){
						try {
							f.close();
							f = null;
						} catch (IOException e1) {
							e.printStackTrace();
						}
					}
					if(outs != null){
						try {
							outs.close();
							outs = null;
						} catch (IOException e1) {
							e.printStackTrace();
						}
					}
				
				}
				if(target!=null){
					return dir.getParentFile().getParentFile().getName()
							+ File.separatorChar + dir.getParentFile().getName()
							+ File.separatorChar + dir.getName() + File.separatorChar
							+ target.getName();
				}
			
			}catch(FileNotFoundException e){
				e.printStackTrace();
				log.error(e);				
			}
		}
		return null;

	}
	
	public synchronized static byte[] filetoArray(File f){
		InputStream in = null;
		try {
			in = new FileInputStream(f);
			ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);
			byte[] bt = new byte[1024];
			int limit = 0;
			while ((limit = in.read(bt)) > -1) {
				buf.put(bt, 0, limit);
			}
			return buf.array();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error(e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
		}finally{
			if(in != null){
				try {
					in.close();
					in = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return new byte[]{};
	}
	
	public synchronized static byte[] filetoArray(InputStream in){
		try {
			ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);
			byte[] bt = new byte[1024];
			int limit = 0;
			while ((limit = in.read(bt)) > -1) {
				buf.put(bt, 0, limit);
			}
			return buf.array();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error(e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
		}finally{
			if(in != null){
				try {
					in.close();
					in = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return new byte[]{};
	}
	
 	/**
	 * 生成照片名方法
	 * @Title: makePhotoName 
	 * @param parent
	 * @return
	 */
	public static String makePhotoName(){

		DateFormat df = new SimpleDateFormat("hhmmss");
		return "photo-"+UUID.randomUUID()+"-"+df.format(new Date());
	}
	/**
	 * 读取文件
	 * @Title: readFile 
	 * @param filename
	 * @return
	 * @throws FileNotFoundException
	 */
	public static InputStream readFile(String filename){
		
		try {
			if(root == null){
				log.error("照片根目录无效!读取照片失败!");
				return null;
			}
			return new FileInputStream(root.getPath()+File.separatorChar+filename);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error("读取文件失败", e);
		}
		return null;
	}
	public static void main(String args[]){}
}

Action类:

/**
 * 照片上传方法
 * @Title: upload 
 * @return
 * @throws Exception 
 */
	public String upload() throws Exception{
		try{
			if("SWF".equals((String)super.getQueryMap().get("SWF"))){
				
				errMsg = siteReportPhotoService.upload(Filedata,ServletActionContext.getRequest(),ServletActionContext.getResponse(), super.getQueryMap());
			}else{
				if(parm.get("__terminal_type") == null)
					parm.put("__terminal_type",(String)super.getQueryMap().get("__terminal_type"));
				retMap = siteReportPhotoService.upload(files,filenames, filetypes,ServletActionContext.getRequest(),ServletActionContext.getResponse(), parm);
				
			}
		}catch(Exception e){
			e.printStackTrace();
			errMsg = e.getMessage();
		}
		return "upload";
	}

三。Service层:

public String upload(File file,ServletRequest request, ServletResponse response, Map map)throws Exception  {
//	int termialType = (int)(map.get("__terminal_type") == null || !((String)map.get("__terminal_type")).matches("\\d+") ? 0 : Integer.parseInt((String)map.get("__terminal_type")));//终端类型:1:手机端
	List fileList = dao.query(map);

	String Filename = (String)map.get("Filename");
	String fname = Filename.substring(0,Filename.lastIndexOf("."));
	String ftype = Filename.substring(Filename.lastIndexOf(".")+1);
	for(int a = 0;a<fileList.size();a++){
		Map m = (Map)fileList.get(a);
		if(fname != null && fname.equals(m.get("PHOTO_NAME"))){
			return "已存在相同名称的照片";
		}
	}
	boolean wresult = fileWrite(map,file, fname,ftype);
	if(!wresult){
		return "后台处理异常";
	}
	return null;
}
}
<pre name="code" class="java">/**
 * 写入数据
 * @Title: fileWrite 
 * @param map
 * @param f
 * @param fname
 * @param ftype
 * @throws Exception
 */
	private boolean fileWrite(Map map, File f, String fname, String ftype)
			throws Exception {

		if (f != null) {
			if(PhotoUtil.MAX_SIZE >= f.length()){
				Map temp = new HashMap();
				temp.putAll(map);
				if (PhotoUtil.STORE_TYPE.equals(PhotoUtil.DATABASE_STORE)) {
					temp.put("PHOTO_CONTENT", PhotoUtil.filetoArray(f));
				} else if (PhotoUtil.STORE_TYPE.equals(PhotoUtil.FILE_STORE)) {
					temp.put("PHOTO_DIR", PhotoUtil.fileStore(f));
				}
				temp.put("PHOTO_PERSION", Util.getInstance().getUserInfo()
						.getUserID());
				temp.put("UPLOADER", Util.getInstance().getUserInfo().getUserID());
				temp.put("STORE_TYPE", PhotoUtil.STORE_TYPE);
				temp.put("PHOTO_NAME", fname);
				temp.put("IMG_TYPE", ftype);
				dao.upload(temp);
				map.put("ID", temp.get("ID"));
				return true;
			}
		}
		return false;
	}

 

前端页面:

swf.js

$(document).ready(function() {
	swfupload = new SWFUpload(
			{ 
		            upload_url: "/cpm/functions/sitereportphoto/uploadSiteReportPhotoAction.action",  
		            post_params: {
		            	 SWF:'SWF',
		            	 SITE_TYPE : parm['parm.DICT_TYPE'],
		            	 SITE_ID : parm['parm.SITE_ID'],
		            	 PROJECT_ID : parm['parm.PROJECT_ID'],
		            	 PHOTO_TYPE : parm['parm.TYPE'],
		            	 PHOTO_POSITION : parm['parm.POSITION']
		            	 },  
		            use_query_string:true,//这块必须设置,要不然在后台处理的时候是没法获得name的值的  
		            // File Upload Settings  
		            file_size_limit : "2 MB",  // 文件大小控制  
		            file_types : "*.JPG;*.JPEG;*.PNG;*.BMP;*.GIF",  
		            file_types_description : "All Files", 
		            file_upload_limit : 20, 
		            file_queue_limit : 20,
		            file_queue_error_handler : fileQueueError,  
		            file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交  
		            file_queued_handler : fileQueued, 
		            upload_start_handler : uploadStart,  
		            upload_progress_handler : uploadProgress,  
		            upload_error_handler : uploadError,  
		            upload_success_handler : uploadSuccess,  
		            upload_complete_handler : uploadComplete,
//		            button_image_url: "img/reload.png",
		            button_placeholder_id : "spanButtonPlaceholder",
		            button_width: '100%',  
		            button_height: '100%',  
		            button_text : '<span class=\'swf_btn\'>照片上传</span>',  
		            button_text_style : '',  
		            button_text_top_padding: ie5?6:8,
		            button_text_left_padding: 8,  
		            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,  
		            button_cursor: SWFUpload.CURSOR.HAND,  		              
		            // Flash Settings  
		            flash_url : "../../components/SWFUPLOAD v2.2.0/swfupload.swf",  

		            custom_settings : {  
		                /*upload_target : "divFileProgressContainer" ,
		                progressTarget:"divFileProgressContainer2" ,*/
		                QUEUE:[],
		                progressContainer:new progressContainer ("divFileProgressContainer")
		            },  
		            // Debug Settings  
		            debug: false
			}	
			);
	
	$(window).unload(function(){if(swfupload){
		swfupload.destroy();		
		}})
	});

var swfupload;
function fileDialogComplete(numFilesSelected, numFilesQueued){

	if(!numFilesSelected || !numFilesQueued/* || !confirm("确定上传您选择的"+numFilesSelected+"张图片文件?")*/){
		this.customSettings.progressContainer.disappear();
		return;

	}
	this.startUpload();

}
function fileQueued(file){
	/*if(file.name.substring(0,file.name.lastIndexOf('.')).length>20){
		this.cancelUpload(file.id,"文件名太长")
	}*/
	this.customSettings.QUEUE.push(file);
	this.customSettings.progressContainer.addProgressBar(file.id,file.name);
}
function fileQueueError(file, errorCode, message){
	var error;
	switch(errorCode){
	case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED :error = "选择的文件过多,超出了预设值(20)!";break;
	case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT :error = "文件太大,超出了预设值(2MB)!";break;
	case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE :error = "空文件!";break;
	case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE :error = "无效类型!";break;
		default:error = ''+message;
	}
	this.customSettings.progressContainer.addInvalidMessage("文件:"+(file||{name:""}).name+" 预处理失败:"+error);
}
function uploadStart(file){
	
	this.customSettings.progressContainer.startUpload(file.id);
}
function uploadProgress(file, bytesComplete, bytesTotal){
	this.customSettings.progressContainer.uploadProgress(file.id, bytesComplete, bytesTotal);
}
function uploadError(file, errorCode, message){
	var error;
	switch(errorCode){
	case SWFUpload.UPLOAD_ERROR.HTTP_ERROR :error = "http错误";break;
	case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL :error = "丢失上传地址";break;
	case SWFUpload.UPLOAD_ERROR.IO_ERROR :error = "IO错误";break;
	case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR :error = "安全问题";break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED :error = "超出上传限制";break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED :error = "上传失败";break;
	case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND :error = "指定的文件id不存在";break;
	case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED :error = "文件验证失败";break;
	case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED :error = "文件已经被取消";break;
	case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED :error = "上传被停止";break;	
		default:error = ''+message;
	}
	this.customSettings.progressContainer.uploadError(file.id, error);
}
function uploadSuccess(file, serverData){
	try{
		eval("var data = "+serverData||"{}")
		if(data.errMsg){
			var stats = this.getStats();
			stats.successful_uploads--;
			stats.upload_errors++;
			this.setStats(stats);
			this.customSettings.progressContainer.uploadError(file.id, data.errMsg);
		}else
			this.customSettings.progressContainer.uploadSuccess(file.id);
	}catch(e){
		this.customSettings.progressContainer.uploadError(file.id, "返回值解释异常");
	}

}
function uploadComplete(file){
	this.customSettings.QUEUE.pop(file);
	if(this.customSettings.QUEUE.length)
		this.startUpload();
	else
		this.customSettings.progressContainer.disappear(this.getStats().successful_uploads);

}

function progressContainer(){
	var _id = "#"+arguments[0];
	if(!$(_id)[0]){
		$(document.body).append("<div id=\"divFileProgressWrapper\" style=\"z-index:2;position:absolute;top:0;left:0;width:100%;height:100%;background-color:white;\"><div id=\"ucloser\"></div><div id="+arguments[0]+"></div></div>").children(":last").contextmenu(function(){return false;})
		$(window).resize(function(){
			$(_id).css({left:(($(_id).parent().width()-450)/2)}).prev().css({right:(($(_id).parent().width()-450)/2)-12})
		});
	}
	$(_id).prev().css({position:'absolute',width:'24px',height:'24px',top:88,right:(($(_id).parent().width()-450)/2)-12,border:'0 solid grey',"z-index":3,"background":"url(img/ucloser.png) center center white","cursor":"pointer"}).hide().parent().hide();
	$(_id).css({position:'absolute',width:'450px',height:'auto','max-height':460,top:100,left:(($(_id).parent().width()-450)/2),border:'1px solid grey',"background-color":"white"});
	$(_id).append("<div id='invalidWrapper'></div>").children(":last").css({width:'100%',height:'auto','max-height':120,overflow:'auto'});
	$(_id).append("<div id='progressWrapper'></div>").children(":last").css({width:'100%',height:'auto','max-height':340,overflow:'auto'});
	var invalidWrapper = $("#invalidWrapper");
	var progressWrapper = $("#progressWrapper");
	this.disappear = function(reload){
		$(_id).prev().click(function(){
			$(this).hide().parent().hide().find('#invalidWrapper,#progressWrapper').empty();
			if(reload){
				window.location.reload();
			}
		}).show().attr("title","点击关闭当前文件上传信息显示面板");
	};
	this.show = function(){
		if($(_id).parent().is(":hidden"))
			$(_id).parent().show();
	};
	this.addInvalidMessage = function(message){
		this.show()
		var  l = invalidWrapper.append("<span style='margin:4px 8px;display:block;color:red;'>"+(message||"")+"</span>").children(":last");
		var t = l[0].offsetTop;
		if(t > invalidWrapper.height()){
			invalidWrapper[0].scrollTop = t;
		}
	};
	this.addProgressBar = function(fileid,filename){
		this.show()
		progressWrapper.append("<div id=file_"+fileid+" style='height:auto;width:100%;margin:2px 0;'>" +
				"<div title='预处理中' style='width:auto;height:20px;line-height:20px;margin:0 8px;overflow:hidden;'>" +
					"文件:<span style='margin:0 4px;'>"+filename+"</span>" +
					"<span>预处理中</span>" +
				"</div>" +
				"<div style='display:none;padding:0;margin:0;border-width:0;'>" +
				"<span style='display:inline-block;text-align:center;line-height:14px;width:0;height:14px;background-color:gold;'></span>" +
				"</div>" +
				"</div>")
	};
	this.startUpload = function(fileid){
		var fdiv = progressWrapper.find("#file_"+fileid);
		fdiv.find("div:first").attr("title","开始上传").find(" span:last").text("开始上传");
		fdiv.find("div:last").show().css({width:'auto',height:'18px',margin:'2px 8px'});
		var t = fdiv[0].offsetTop;
		if(t > progressWrapper.height()){
			progressWrapper[0].scrollTop = t;
		}
		
	};
	this.uploadProgress = function(fileid, bytesComplete, bytesTotal){
		progressWrapper.find("#file_"+fileid).find("div:first").attr("title","上传中 ("+bytesComplete/bytesTotal*100+"%)").find("span:last").text("上传中 ("+bytesComplete/bytesTotal*100+"%)");
		progressWrapper.find("#file_"+fileid).find("div:last").find("span:first").css({width:(bytesComplete/bytesTotal)*(434)+"px"});
	};
	this.uploadError = function(fileid, message){
		progressWrapper.find("#file_"+fileid).find("div:first").attr("title","上传失败:"+message||"").find("span:last").text("上传失败:"+message||"").css({'color':"red"});
		progressWrapper.find("#file_"+fileid).find("div:last span:first").css({"background-color":"red"});
	};
	this.uploadSuccess = function(fileid){
		progressWrapper.find("#file_"+fileid).find("div:first").attr("title","上传成功").find("span:last").text("上传成功").css({'color':"green"});
		progressWrapper.find("#file_"+fileid).find("div:last span:first").css({"background-color":"green"});

	};
	this.uploadComplete = function(){
		
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值