当前位置: 代码迷 >> Web前端 >> uploadify3.2+struts2文件下传
  详细解决方案

uploadify3.2+struts2文件下传

热度:4091   发布时间:2013-02-26 00:00:00.0
uploadify3.2+struts2文件上传

HTML页面

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><!-- 引入uploadify需要的css文件 --><link rel="stylesheet" type="text/css" href="css/uploadify.css"/></head><body>    	        <!-- 上传按钮 -->        <input type="file" id="upload-button" />    <!-- 上传 这里*也可以重写你需要的参数 -->    <a href="javascript:$('#upload-button').uploadify('upload','*')">开始上传</a>    <!-- 引入需要的JS文件 --><script type="text/javascript" src="js/jquery-1.8.2.js"></script><script type="text/javascript" src="js/jquery.uploadify.js"></script><script type="text/javascript" src="js/upload.js"></script></body></html>

JS

$('#upload-button').uploadify({      'width': '265',      'height': '65',      'buttonText': '上传图片',      'auto': false, //不自动提交      'swf': 'images/uploadify.swf',                      //falsh上传图片      'uploader': 'upload.do',                                //上传处理,连接后台      'fileTypeDesc': 'Supported File Format',     //文件类型描述      'fileTypeExts': '*.jpg;*.jpge;*.gif;*.png',     //上传文件类型      'fileSizeLimit': '10MB', //文件最大大小      'fileObjName': 'file',  //后台接受文件对象名,保持一致      'formData':{'id':1,'name':'irwin'}, //测试附加数据      'onSelectError': function(file, errorCode, errorMsg){ //file选择失败后触发          alert(errorMsg);      },      'onFallback': function(){ //flash报错触发          alert("请您先安装flash控件");      },      'onUploadSuccess': function(file, data, response){ //上传成功后触发          if("sizeError" == data){              alert("文件大小不能超过10M");          } else if("typeError" == data){              alert("不支持的文件类型");          }      }});

Struts代码,action

package com.rying.dms.web.action;import java.io.File;import java.io.PrintWriter;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;import com.rying.dms.util.UploadUtil;public class UploadAction extends ActionSupport{    private static Logger logger = Logger.getLogger(UploadAction.class);    private static final long serialVersionUID = -3455411632907896807L;    private File file;    private String fileFileName;    @Override    public String execute(){        PrintWriter out = null;        try {            HttpServletResponse response = ServletActionContext.getResponse();            response.setContentType("text/html;charset=utf-8");            out = response.getWriter();           //test参数用来测试的路径名           UploadUtil.upload("test", file, fileFileName);        } catch (Exception e) {            logger.error("upload files error",e);            out.print(e.getMessage());        }        return null;    }    public File getFile() {        return file;    }    public void setFile(File file) {        this.file = file;    }    public String getFileFileName() {        return fileFileName;    }    public void setFileFileName(String fileFileName) {        this.fileFileName = fileFileName;    }}


上传Util类代码,配置文件

配置文件:

#server pathdocBase=D:\\uploadfileType=jpg,bmp,gif,png,jpeg,doc,pdf,exe,docx,avi,mp4,mp3,rmvb,3gp,swf#the size is KBmaxSize=10240#Thumbnail paththumbnailPath=thumbnailthumbnailWidth=100thumbnailHeight=80


Util工具类:

package com.rying.dms.util;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;import java.util.UUID;import javax.imageio.ImageIO;import org.apache.log4j.Logger;import com.rying.dms.exception.UploadException;import com.rying.dms.exception.UploadSizeException;import com.rying.dms.exception.UploadTypeException;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;public class UploadUtil {    private static Logger logger = Logger.getLogger(UploadUtil.class);       //这里定义一些错误信息的常量    private static final String SIZE_ERROR = "sizeError";    private static final String TYPE_ERROR = "typeError";    private static final String UPLOAD_ERROR = "uploadError";    private static String maxSize;    private static String fileType;    private static String docBase;    private static String thumbnailPath;    private static String thumbnailWidth;    private static String thumbnailHeight;    /**     * Upload file util     *     * @author Irwin.Ai     * @throws UploadTypeException, UploadSizeException     */    public static void upload(String folderPath,File file, String fileName) throws UploadException, UploadTypeException, UploadSizeException {        FileInputStream fis = null;        FileOutputStream fos = null;        try {            //读取配置文件            fis = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("/").getPath().replace("%20", " ") + "/upload.properties");            Properties pro = new Properties();            pro.load(fis);            docBase = pro.getProperty("docBase");            maxSize = pro.getProperty("maxSize");            fileType = pro.getProperty("fileType");            thumbnailPath = pro.getProperty("thumbnail");            thumbnailWidth = pro.getProperty("thumbnailWidth");            thumbnailHeight = pro.getProperty("thumbnailHeight");            //验证文件类型            String fileExt = "";            // 获得文件扩展名            if (fileName.lastIndexOf(".") >= 0) {                fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);            }            // 验证文件类型            logger.info("file extend name = " + fileExt + ", support file type = " + fileType);            if (("," + fileType.toLowerCase() + ",").indexOf("," + fileExt.toLowerCase() + ",") < 0) {                logger.warn("文件类型错误");		//类型验证错误,抛出异常,在action层捕获到,前台根据错误信息判断显示错误信息                throw new UploadTypeException(TYPE_ERROR, new UploadTypeException());            }            //验证文件大小            fis = new FileInputStream(file);            Integer size = fis.available();            logger.info("file size = " + (size / 1024) + ", max size = " + maxSize);            if (size > Integer.parseInt(maxSize) * 1024) {                logger.warn("文件大小不能超过10M");                throw new UploadSizeException(SIZE_ERROR, new UploadSizeException());            }            //创建文件目录            //重命名文件            String newFileName = UUID.randomUUID().toString();            //保存路径            String saveDir = docBase + "/" + folderPath;            //目录不存在则创建            File fileDir = new File(saveDir);            if (!fileDir.exists()) {                fileDir.mkdirs();            }            //保存文件到服务器            //文件保存路径            String savePath = saveDir + "/" + newFileName + "." + fileExt;            logger.info("save path = " + savePath);            fos = new FileOutputStream(savePath);            byte buffer[] = new byte[size];            int len = 0;            while ((len = fis.read(buffer)) > 0) {                fos.write(buffer, 0, len);            }            //保存文件到数据库            //--------------------------        } catch (IOException e){            logger.error(UPLOAD_ERROR, e);            throw new UploadException(UPLOAD_ERROR, e);        } finally {            try {                if(null != fos){                    fos.flush();                    fos.close();                }                if(null != fis){                    fis.close();                }            } catch (IOException e) {               logger.error("close stream error");            }        }    }    //创建缩略图    public static void createThumbnail(File file, String fileExt)            throws UploadException {        try {            Image img = ImageIO.read(file);            BufferedImage image = new BufferedImage(                    Integer.parseInt(thumbnailWidth),                    Integer.parseInt(thumbnailHeight),                    BufferedImage.TYPE_INT_RGB);            image.getGraphics().drawImage(img, 0, 0,                    Integer.parseInt(thumbnailWidth),                    Integer.parseInt(thumbnailHeight), null);            String saveDir = docBase + "/" + thumbnailPath;            File fileDir = new File(saveDir);            if (!fileDir.exists()) {                fileDir.mkdirs();            }            String newFileName = file.getName();            String savePath = saveDir + "/" + newFileName + "." + fileExt;            FileOutputStream fos = new FileOutputStream(savePath);            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);            JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam(image);            param.setQuality(1f, true);            encoder.encode(image, param);            fos.close();        } catch (Exception e) {            logger.error("create thumbnail error." + e);            throw new UploadException("create thumbnail error." + e);        }    }}

页面效果:



  相关解决方案