jquery-uploadify使用

本文介绍了如何在Struts2 MVC框架中集成并使用jQuery-Uploadify上传插件,包括拦截器判断、文件上传流程、图片路径处理及删除功能。详细阐述了上传文件的配置与实现,提供了实例代码解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jquery-uploadify 在struts2mvc下使用:

若用户中心使用 上传插件,会被struts2 mvc的Interceptor用户拦截器所拦截,所以需要在拦截器中判断类型。

String agent = request.getHeader("user-agent");

判断类型是否为:Shockwave Flash 同时判断当前用户是否登录 。一般的登录用 session或者cookies 实现,具体自己研究。

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.col.sesame.common.config.AppConfig;
import com.col.sesame.common.util.FileUpload;
import com.col.sesame.common.util.UserToken;


public class ImageUtilAction {
	
	/**上传文件**/
    private File uploadify;
	/**上传文件名**/
    private String uploadifyFileName;
	/** 图片放置模块*/
    private String module;
    /** 图片名称 */
    private String imageName;
	
	/**上传文件路径地址 */
	private final static String UPLOADDIR = AppConfig.getUploadDir();
	/** 图片服务器显示路径*/
	private final static String IMAGEURLPREFIX = AppConfig.getImageUrlPrefix();
	
	/**
	 * .图片上传
	 * <p>
	 * @return
	 * @throws Exception
	 */
	public String upload() throws Exception {
		PrintWriter pw = null;
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			String fileDir = UPLOADDIR + module + File.separator + getUserInfo().getUserId();
			String fileName = FileUpload.uploadFile(uploadify, fileDir, uploadifyFileName);
			//图片物理路径
			String filePath = fileDir+File.separator+fileName;
			//图片访问路径
			String imagePath = IMAGEURLPREFIX+module+"/"+getUserInfo().getUserId()+"/"+fileName;
			
			map.put("fileName", fileName);
			map.put("filePath", filePath);
			map.put("imagePath", imagePath);
			JSONObject jsonObj = JSONObject.fromObject(map);
			response.setContentType("text/json; charset=utf-8");  
			response.getWriter().print(jsonObj.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("upload image error : " + e.getMessage());
		} finally {
			if(null != pw)
				pw.close();
		}
		return null;
	}
	
	/**
	 * .图片删除
	 * <p>
	 * @return
	 */
	public String delImage(){
		String filePath = UPLOADDIR + module + File.separator + getUserInfo().getUserId()+File.separator+imageName;
		File file = new File(filePath);
		if(file.exists()){
			file.delete();
		}
		return "delImage";
	}
	
	/****
	 * 获取当前用户会员信息
	 */
	private UserInfoBO getUserInfo(){
		UserToken userToken = (UserToken)request.getSession().getAttribute("userToken");
		UserInfoBO userInfo = new UserInfoBO();
		userInfo.setUserId(String.valueOf(userToken.getId()));
		return userInfo;
	}

	public File getUploadify() {
		return uploadify;
	}

	public void setUploadify(File uploadify) {
		this.uploadify = uploadify;
	}

	public String getUploadifyFileName() {
		return uploadifyFileName;
	}

	public void setUploadifyFileName(String uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}
	
	public String getModule() {
		return module;
	}
	
	public String getImageName() {
		return imageName;
	}
	
	public void setImageName(String imageName) {
		this.imageName = imageName;
	}
	
	public void setModule(String module) {
		this.module = module;
	}
}
上传工具

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public class FileUpload {
	
	public static String uploadFile(File file,String uploadDir,String fileFileName)
	{
		String newFileName =null;
		UUID now =UUID.randomUUID();
		File dir = new File(uploadDir);
		if(!dir.exists())
		{
			dir.mkdirs();
		}
		int index = fileFileName.lastIndexOf(".");
		if(index!=-1)
		{
			newFileName=now+fileFileName.substring(index);
		}else
		{
			newFileName=now.toString();
		}
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try{
			FileInputStream fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			
			FileOutputStream fos =  new FileOutputStream(new File(dir,newFileName));
			bos = new BufferedOutputStream(fos);
			
			byte[] buf = new byte[4096];
			
			int len = -1;
			while((len=bis.read(buf))!=-1)
			{
				bos.write(buf,0,len);
			}
		}catch(FileNotFoundException e)
		{
		   e.printStackTrace();	
		   return null;
		} catch (IOException e) {
			e.printStackTrace();
		   return null;
		}
		finally{
			try{
				if(null != bis)
				{
					bis.close();
				}
			}catch(IOException e)
			{
				e.printStackTrace();
			}
			try{
				if(null != bos)
				{
					bos.close();
				}
			}catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		if( newFileName==null ){
			newFileName = ""+new Date().getTime();
		}
		return newFileName;
		
	}
}


spring mvc环境下

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.bcb.cms.site.entity.Site;
import com.bcb.core.constant.SystemConstants;
import com.bcb.core.initialize.SystemSettingCache;
import com.bcb.core.util.DateUtils;
import com.bcb.core.util.UploadUtil;
import com.bcb.front.util.FrontHelper;

@Controller
public class ImageUploadAct {

	@RequestMapping(value = { "/image_upload.jspx", "/**/image_upload.jspx" })
	public void uploadImg(String typename, Boolean isRename, Boolean isSystem,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		isRename = isRename == null ? true : isRename; // 是否重命名
		isSystem = isSystem == null ? false : true;
		Map mapPath = new HashMap();
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		MultipartResolver resolver = new CommonsMultipartResolver(request
				.getSession().getServletContext());
		commonsMultipartResolver.setDefaultEncoding("utf-8");
		Site site = FrontHelper.getSite(request);
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartRequest = resolver
					.resolveMultipart(request);
			Iterator<String> iter = multipartRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multipartRequest.getFile((String) iter
						.next());
				System.out.println("开始上传………………………………");
				if (typename != null && !typename.equals("")) {
					mapPath = this.disposeFilePath(file, site, typename,
							isRename, false, isSystem);
				} else {
					mapPath = this.disposeFilePath(file, site, null, isRename,
							false, isSystem);
				}
				System.out.println("上传 : " + mapPath);
				JSONObject jsonObj = JSONObject.fromObject(mapPath);
				response.setContentType("text/json; charset=utf-8");
				response.getWriter().print(jsonObj.toString());
			}
		}
	}

	/**
	 * 物理删除图片
	 * 
	 * @param imagePath
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/image_delImg.jspx", "/**/image_delImg.jspx" })
	@ResponseBody
	public boolean deleteImg(String imagePath, HttpServletRequest request)
			throws Exception {
		boolean delFlag = false;
		if (null != imagePath && !"".equals(imagePath)) {
			String[] path = imagePath.split(",");
			imagePath = "";
			int uploadindex = 0;
			for (String p : path) {
				uploadindex = p.indexOf(SystemConstants.SITE_ROOT);
				uploadindex = uploadindex > 0 ? uploadindex + 7 : 0;
				imagePath += p + "/";
			}
			if (!"".equals(imagePath)) {
				imagePath = imagePath.substring(uploadindex,
						imagePath.length() - 1);
				// 图片文件的完成路径
				String fullImagePath = SystemSettingCache.getCache(
						SystemSettingCache.SYSTEM_SETTING_KEY).getUploadPath()
						+ imagePath;
				if (null != fullImagePath && !("").equals(fullImagePath)) {
					File file = new File(fullImagePath);
					if (file.isFile()) {
						file.delete();
						delFlag = true;
					}
				}
			}
		}
		return delFlag;
	}

	/**
	 * 处理上传完成后的图像存储路径
	 * 
	 * @param imgFile
	 * @param sitePath
	 * @return
	 */
	public Map<String, String> disposeFilePath(MultipartFile imgFile,
			Site site, String ownFolder, Boolean isRename, Boolean isAddMark,
			Boolean isSystem) {
		Map<String, String> mapPath = new HashMap<String, String>();
		// 保存的文件名
		String fileName = "";
		String dirName = "";
		// 上传路径
		String uplodDir = "";
		// 上传成功后返回的File
		File file = null;
		// 截取上传成功后的路径
		String uploadSuccessPath = "";
		String relativePath = "";
		String siteCode = "";
		if (!isSystem) {
			siteCode = site.getSiteCode() + File.separator;
		} else {
			siteCode = "";
		}
		Boolean isCreateFolder = ownFolder == null ? true : false;
		if (isRename) {
			uplodDir = SystemSettingCache.getCache(
					SystemSettingCache.SYSTEM_SETTING_KEY).getUploadPath()
					+ siteCode + SystemConstants.UPLOAD_DIR;
			fileName = DateUtils.formaterDate(new Date(), "yyyyMMddHHmmssSS");

		} else {
			uplodDir = SystemSettingCache.getCache(
					SystemSettingCache.SYSTEM_SETTING_KEY).getUploadPath()
					+ siteCode;
			fileName = imgFile.getOriginalFilename();

		}
		if (isCreateFolder) {
			dirName = DateUtils.formaterDate(new Date(), "yyyyMMdd") + "/";
			uplodDir += dirName;
		} else {
			if (!ownFolder.endsWith("/")) {
				dirName = ownFolder + "/";
			}
			if (dirName.startsWith("/")) {
				dirName = dirName.replaceFirst("^/+", "");
			}
			uplodDir += dirName;
		}
		file = UploadUtil.uploadFile(imgFile, uplodDir, fileName);

		if (null != file) {
			mapPath.put("filename", file.getName());
			mapPath.put("filepath", file.getAbsolutePath());
		} else {
			mapPath.put("filename", "");
			mapPath.put("filepath", "");
		}
		return mapPath;
	}

}



上传工具:

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
	
	/**
	 * 通过传入页面读取到的文件,并返回一个已经创建好的File
	 * 
	 * @param imgFile       要保存的文件
	 * @param uploadPath    文件将要存放的路径
	 * @param saveFileName  文件将要保存的名字,名字不包括文件的类型(saveAs.jpg只需要saveAs)
	 * @return
	 */
	public static File uploadFile(MultipartFile imgFile, String uploadPath, String saveFileName) {
		
		File dir = new File(uploadPath);
		if(!dir.exists())
		{
			dir.mkdirs();
		}
		
		// 创建文件存放路径
		File file = null;
		if(saveFileName.indexOf(".")!= -1){
			file = new File(uploadPath,saveFileName);
		}else{
			file = new File(uploadPath, getUploadFileName(imgFile, saveFileName));
		}
		
		try {
			if(!file.exists()){
				// 保存上传的文件
				imgFile.transferTo(file); 
			//如果上传文件已上传,返回null
			}else{
				return null;
			}
			
			
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		file.setExecutable(true);
		file.setWritable(true);
		file.setReadable(true);
		return file;
	}
	
	/**
	 * 
	 * 取得新的文件名称
	 * 
	 * @param imgFile
	 * @param saveFileName
	 * @return
	 */
	public static String getUploadFileName(MultipartFile imgFile, String saveFileName) {
		
		// 取得上传的文件名
		String fileName = imgFile.getOriginalFilename();
		
		// 取得上传文件的类型,并重新命名
		saveFileName = saveFileName + fileName.substring(fileName.lastIndexOf("."), fileName.length());
		
		return saveFileName;
	}
	
	public static File uploadFile(MultipartFile imgFile, String uploadPath) {
		return uploadFile(imgFile, uploadPath, genSystemFileName());
	}
	
	public static String genSystemFileName() {
		StringBuilder filename = new StringBuilder("pic-");
		filename.append(String.valueOf(System.currentTimeMillis()));
		
		Random random = new Random();
		filename.append(String.valueOf(random.nextInt(100000)));
		
		return filename.toString();
	}

}
jquery-uploadify 的配置简单描述:

$(document).ready(function() {
    $("#file_upload").uploadify({
        //开启调试
        'debug' : false,
        //是否自动上传
        'auto':false,
        //超时时间
        'successTimeout':99999,
        //附带值
        'formData':{
            'userid':'用户id',
            'username':'用户名',
            'rnd':'加密密文'
        },
        //flash
        'swf': "uploadify.swf",
        //不执行默认的onSelect事件
        'overrideEvents' : ['onDialogClose'],
        //文件选择后的容器ID
        'queueID':'uploadfileQueue',
        //服务器端脚本使用的文件对象的名称 $_FILES个['upload']
        'fileObjName':'upload',
        //上传处理程序
        'uploader':'imageUpload.php',
        //浏览按钮的背景图片路径
        'buttonImage':'upbutton.gif',
        //浏览按钮的宽度
        'width':'100',
        //浏览按钮的高度
        'height':'32',
        //expressInstall.swf文件的路径。
        'expressInstall':'expressInstall.swf',
        //在浏览窗口底部的文件类型下拉菜单中显示的文本
        'fileTypeDesc':'支持的格式:',
        //允许上传的文件后缀
        'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png',
        //上传文件的大小限制
        'fileSizeLimit':'3MB',
        //上传数量
        'queueSizeLimit' : 25,
        //每次更新上载的文件的进展
        'onUploadProgress' : function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
             //有时候上传进度什么想自己个性化控制,可以利用这个方法
             //使用方法见官方说明
        },
        //选择上传文件后调用
        'onSelect' : function(file) {
                  
        },
        //返回一个错误,选择文件的时候触发
        'onSelectError':function(file, errorCode, errorMsg){
            switch(errorCode) {
                case -100:
                    alert("上传的文件数量已经超出系统限制的"+$('#file_upload').uploadify('settings','queueSizeLimit')+"个文件!");
                    break;
                case -110:
                    alert("文件 ["+file.name+"] 大小超出系统限制的"+$('#file_upload').uploadify('settings','fileSizeLimit')+"大小!");
                    break;
                case -120:
                    alert("文件 ["+file.name+"] 大小异常!");
                    break;
                case -130:
                    alert("文件 ["+file.name+"] 类型不正确!");
                    break;
            }
        },
        //检测FLASH失败调用
        'onFallback':function(){
            alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
        },
        //上传到服务器,服务器返回相应信息到data里
        'onUploadSuccess':function(file, data, response){
            alert(data);
        }
    });
});


以上代码只可作为参考 不可直接使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值