struts2+uploadify上传文件

common.uploadPhoto=function(){
    $("#uploadFile").uploadify({  
        swf: /ecp/res/web/plugins/uploadify/uploadify.swf,      //[必须设置]swf的路径
        uploader:common.uploader,  //[必须设置]上传文件触发的url
        buttonImg:/ecp/res/web/img/152743_719516335.png,
        width: 120,                                          //设置浏览按钮的宽度 ,默认值:110
        height:25,                                            //设置浏览按钮的高度, 默认值:30。
        fileObjName:file,                                  //上传文件name
        auto:common.flag,                                      //设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传
        buttonText: 选择上传图片 ,                          //浏览按钮的文本,默认值:BROWSE 
        multi: true,                                      //设置为true时可以上传多个文件
        queueID: some_file_queue,                  //文件队列的ID,该ID与存放文件队列的div的ID一致
        fileTypeExts:*.jpg;*.jpge;*.gif;*.png;*.bmp,      //允许上传的文件后缀  
        fileSizeLimit:5MB,                              //上传文件的大小限制  
        queueSizeLimit: common.queueSizeLimit,                                  //上传数量  
        progressData : all,                            //队列中显示文件上传进度的方式:all-上传速度+百分比,percentage-百分比,speed-上传速度
        removeCompleted : true,                    //上传成功后的文件,是否在队列中自动删除
        method:post,                                    //和后台交互的方式:post/get
        onUploadSuccess: function(file, data, response){
                data= eval(( + data + ));  
                common.showPhoto(file,data);
                var url=data.newImgPath[0];
                url=url.substring(url.lastIndexOf("/"),url.length);
                var oldnames=$("#oldnames").val();
                var newnames=$("#newnames").val();
                if(oldnames=="" ||oldnames==null){
                    oldnames="/"+file.name;
                }else{
                    oldnames=oldnames+";/"+file.name;
                }
                if(newnames=="" || newnames==null){
                    newnames=url; 
                }else{
                    newnames=newnames+";"+url;
                }
                $("#oldnames").val(oldnames);
                $("#newnames").val(newnames);
                common.uploadSize+=1;
        },
        onFallback:function(){  
                alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");  
        },
        //当每个文件添加至队列后触发
        onSelect :function(file){
                /*alert( ‘id: ‘ + file.id+ ‘ - 索引: ‘ + file.index+ ‘ - 文件名: ‘ + file.name
                    + ‘ - 文件大小: ‘ + file.size+ ‘ - 类型: ‘ + file.type+ ‘ - 创建日期: ‘ + file.creationdate
                    + ‘ - 修改日期: ‘ + file.modificationdate+ ‘ - 文件状态: ‘ + file.filestatus); */
        },
        //当队列中的所有文件全部完成上传时触发
        onQueueComplete : function(stats){
             /*alert( ‘成功上传的文件数: ‘ + stats.uploadsSuccessful
                + ‘ - 上传出错的文件数: ‘ + stats.uploadsErrored); */
            common.uploadSuccess();
        },
        //当文件选定发生错误时触发
        onSelectError:function(file, errorCode, errorMsg){  
                switch(errorCode) {  
                    case -100:  
                        alert("上传的文件数量已经超出系统限制的"+$(#uploadFile).uploadify(settings,"queueSizeLimit")+"个文件!");  
                        break;  
                    case -110:  
                        alert("文件 ["+file.name+"] 大小超出系统限制的"+$(#uploadFile).uploadify(settings,fileSizeLimit)+"大小!");  
                        break;  
                    case -120:  
                        alert("文件 ["+file.name+"] 大小异常!");  
                        break;  
                    case -130:  
                        alert("文件 ["+file.name+"] 类型不正确!");  
                        break;  
                }
                $("#some_file_queue").empty();
                /* alert( ‘id: ‘ + file.id+ ‘ - 索引: ‘ + file.index+ ‘ - 文件名: ‘ + file.name
                    + ‘ - 文件大小: ‘ + file.size+ ‘ - 类型: ‘ + file.type+ ‘ - 创建日期: ‘ + file.creationdate
                    + ‘ - 修改日期: ‘ + file.modificationdate+ ‘ - 文件状态: ‘ + file.filestatus
                    + ‘ - 错误代码: ‘ + errorCode+ ‘ - 错误信息: ‘ + errorMsg); */
        },
        onDialogClose : function(swfuploadifyQueue) {//当文件选择对话框关闭时触发
            if(swfuploadifyQueue.filesSelected<common.queueSizeLimit){
                if(swfuploadifyQueue.filesSelected>common.queueSizeLimit-common.uploadSize){
                    $("#uploadFile").uploadify(cancel,*);
                    alert("上传的文件数量已经超出系统限制的"+$(#uploadFile).uploadify(settings,"queueSizeLimit")+"个文件!");  
                }
            }
        },
        onUploadStart: function (file) {  
            common.onUploadStart();
        }

    });  
    if(!common.flag)
    common.uploadBind();
};

<div>
                      <div id="some_file_queue" style="display:none"></div> 
                     <input type="file" name="file" id="uploadFile" />
 </div>

 struts文件配置

<!-- 上传 -->
 <package name="upload" namespace="/bs-ui/upload" extends="bs">
  <action name="*!*" class="com.daasan.ecp.upload.{1}" method="{2}">
       <result type="json" />
          <result name="upload" type="json">
             <param name="excludeProperties">file,fileContentType,fileFileName</param>
          </result>
     </action>
 </package>

public class UploadAction extends ActionSupport
{
    /*
     * 成员变量的名称不能随意更改, 
     * private File file;                 变量的名称必须和jsp中上传文件标签中的name属性的值一致.
     * private String fileFileName;        变量的名称必须为"上传文件的名称+FileName".
     * private String fileContentType;    变量的名称必须为"上传文件的名称+ContentType", 
     */
    private static final long serialVersionUID = 1L;

    private List<File> file;

    private List<String> fileFileName;

    private List<String> fileContentType;
    
    private List<String> newImgPath = new ArrayList<String>();
    
    private String id;
    
    public String uploadFileTemp()
    {
        Map<String, String> map=UploadUtil.getEcpDir();
        String url=ServletActionContext.getRequest().getContextPath()+map.get("uploadTemp")+"/";
        for(int i=0;i<file.size();i++)
        { 
            newImgPath.add(url+UploadUtil.upload(file.get(i), fileFileName.get(i),map.get("uploadTemp")));
        }
        return "upload";
    }
    
    public String uploadAlbumPhoto()
    {
        try {
        Map<String, String> map=UploadUtil.getEcpDir();
        HttpServletRequest request=ServletActionContext.getRequest();
        String url=ServletActionContext.getRequest().getContextPath()+map.get("uploadTemp");
        EcpFtpUtil.connectServer();
        for(int i=0;i<file.size();i++){
            String newName="/"+UploadUtil.upload(file.get(i), fileFileName.get(i),map.get("uploadTemp"));
            newImgPath.add(url+newName);
            String uploadPath=map.get("uploadShopPhoto")+"/"+album.getMember().getId()+"/"+album.getServerName();
            String uploadTempPath=map.get("uploadShopPhoto")+"/"+album.getMember().getId()+map.get("temp")+"/";
            String uploadTemp=request.getRealPath(map.get("uploadTemp"));
            String ext=UploadUtil.getExtention(newName);//后缀
              String name=UploadUtil.getExtName(newName);//截取后缀
              String detail=name+"."+EcpUtil.PHOTO_DETAILWH+ext;
            String thumb=name+"."+EcpUtil.PHOTO_THUMBWH+ext;
            UploadUtil.getftpUpload(newName, uploadPath,uploadTemp);
     }
        EcpFtpUtil.closeConnect();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BsException e) {
            e.printStackTrace();
        }
        return "upload";
    }
    public List<File> getFile() {
        return file;
    }

    public void setFile(List<File> file) {
        this.file = file;
    }

    public List<String> getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(List<String> fileFileName) {
        this.fileFileName = fileFileName;
    }


    public List<String> getFileContentType() {
        return fileContentType;
    }


    public void setFileContentType(List<String> fileContentType) {
        this.fileContentType = fileContentType;
    }


    public List<String> getNewImgPath() {
        return newImgPath;
    }


    public void setNewImgPath(List<String> newImgPath) {
        this.newImgPath = newImgPath;
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}
/**
 * 图片上传工具类
 * @author Think
 *
 */
public class UploadUtil {
	private static String default_config = "/businessConfig/"
			+ "http.properties";
	public static Properties ps = new Properties();

	private static void loadPs() {
		try {
			Class<?> config_class = Class
					.forName("com.daasan.ecp.util.UploadUtil");
			InputStream is = config_class.getClassLoader().getResourceAsStream(
					default_config);
			ps.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// String
		// path="webapp/WEB-INF/classes/ftp.properties";
		/*
		 * String path = ServletActionContext.getServletContext().getRealPath(
		 * "/WEB-INF/classes/businessConfig/http.properties"); File file = new
		 * File(path); InputStream in = null; try { in = new
		 * FileInputStream(file); ps.load(in); } catch (FileNotFoundException e)
		 * { e.printStackTrace(); } catch (IOException e) { e.printStackTrace();
		 * }
		 */
	}

	/**
	 * @param file
	 *            文件
	 * @param fileFileName
	 *            文件名
	 * @param dir
	 *            临时目录
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public static String upload(File file, String fileFileName, String dir) {
		String root = ServletActionContext.getRequest().getRealPath(dir);
		String newPath = getNewPath(getExtention(fileFileName));
		File destFile = new File(root, newPath);
		try {
			FileUtils.copyFile(file, destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return newPath;
	}
	
	/**
	 * 将手机端应用程序APK上传到临时目录(不改变源文件名称)
	 * 
	 * @param file
	 *            文件
	 * @param fileFileName
	 *            文件名
	 * @param dir
	 *            临时目录
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public static String upload2(File file, String fileFileName, String dir) {
		String root = ServletActionContext.getRequest().getRealPath(dir);
		File destFile = new File(root, fileFileName);
		try {
			FileUtils.copyFile(file, destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileFileName;
	}

	/**
	 * @param dir
	 *            临时目录
	 * @param url
	 *            文件路径
	 * @param newDir
	 *            新目录
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static boolean getUploadServer(String dir, String url, String newDir) {
		boolean flag = false;

		String oldUrl = ServletActionContext.getRequest().getRealPath(dir)
				+ url;
		File oldFile = new File(oldUrl);
		File destFile = new File(newDir, url);
		try {
			FileUtils.copyFile(oldFile, destFile);
			deleteFile(oldUrl);
			flag = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

	public static void getftpUpload(String newNames, String uploadPath,
			String uploadTemp) throws IOException {
		EcpFtpUtil.makeDirectory(uploadPath);
		String oldUrl = uploadTemp + newNames;
		File oldFile = new File(oldUrl);
		EcpFtpUtil.ftpUpload(oldFile, uploadPath, newNames.substring(1,newNames.length()));
	}
	
	/**
	 * apk上传使用
	 * */
	public static void getftpUpload2(String newNames, String uploadPath,
			String uploadTemp) throws IOException { 
		EcpFtpUtil.makeDirectory(uploadPath);
		String oldUrl = uploadTemp + newNames;
		File oldFile = new File(oldUrl);
		EcpFtpUtil.ftpUpload(oldFile, uploadPath, newNames.substring(0,newNames.length()));
	}
	
	public static void getFileFtpUpload(File file, String uploadPath,
			String newfileName) throws IOException {
		EcpFtpUtil.connectServer();
    	EcpFtpUtil.makeDirectory(uploadPath);
    	EcpFtpUtil.ftpUpload(file, uploadPath,newfileName);
		EcpFtpUtil.closeConnect();
	}
	public static void batchFtpUpload(String[] newNames, String uploadPath,
			String uploadTemp) throws IOException {
		EcpFtpUtil.makeDirectory(uploadPath);
		for (int i = 0; i < newNames.length; i++) {
			String oldUrl = uploadTemp + newNames[i];
			File oldFile = new File(oldUrl);
			EcpFtpUtil.ftpUpload(oldFile, uploadPath, newNames[i].substring(1,newNames[i].length()));
		}
	};
	public static String getExtention(String fileFileName) {
		int idx = fileFileName.lastIndexOf(".");
		String extention = fileFileName.substring(idx); // 文件后缀
		return extention;
	}

	public static String getExtName(String fileFileName) {
		int idx = fileFileName.lastIndexOf(".");
		String name = fileFileName.substring(0, idx); // 文件后缀
		return name;
	}

	public static String getNewPath(String extention) {
		String time = CalDateUtil.getCurrDate("yyyyMMddHHmmssSSS");
		String newPath = time + extention; // 新的文件名(日期+后缀)
		return newPath;
	}

	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	private static boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	/**
	 * 获取服务器上传目录
	 */
	private static UploadBean getUplodDir() {
		loadPs();
		UploadBean uploadBean = new UploadBean();
		uploadBean.setIp(ps.getProperty("ftp.ip"));
		uploadBean.setPort(ps.getProperty("down.port"));
		uploadBean.setDownIp(ps.getProperty("down.ip"));
		uploadBean.setRemoteDir(ps.getProperty("ftp.remoteDir"));
		uploadBean.setpRootDir(ps.getProperty("project.rootDir"));
				return uploadBean;
	}

	public static Map<String, String> getEcpDir() {
		UploadBean b = getUplodDir();
		String uploadTemp = b.getpRootDir() + b.getPtemp();// 图片上传的临时目录
		String uploadShop = b.getEcpDir() + b.getShop();
		String uploadShopPhoto = uploadShop + b.getImage();// 店铺图片上传目录
				Map<String, String> map = new HashMap<String, String>();
		map.put("uploadTemp", uploadTemp);
		map.put("uploadBrand", uploadBrand);
			return map;
	}
}

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
/**
 * 资源上传到ftp工具类
 * @author Think
 *
 */
public class EcpFtpUtil {
    private static String ip;//FTP服务器hostname 
    
    private static int port;//FTP服务器端口
    
    private static String username;//FTP登录账号 
    
    private static String password;//FTP登录密码 

    public static FTPClient ftpClient; 
    
    private static String remoteDir; //FTP服务器保存目录,如果是根目录则为“/”A
    public final static String default_config = "/businessConfig/"
        + "http.properties";
    /**
     * 初始化参数
     */
    private static void setParam(){
        //String pathPro = ServletActionContext.getServletContext().getRealPath(
                //"/WEB-INF/classes/businessConfig/ftp.properties");
        /*String pathPro="D:/dsworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ecp/WEB-INF/classes/businessConfig/http.properties";
        File file = new File(pathPro);
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            Properties ps = new Properties();
            ps.load(in);
            ip = ps.getProperty("ftp.ip");
            username = ps.getProperty("ftp.username");
            password = ps.getProperty("ftp.password");
            remoteDir = ps.getProperty("ftp.remoteDir");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }*/
        try {
            Class<?> config_class = Class
                    .forName("com.daasan.ecp.util.EcpFtpUtil");
            InputStream is = config_class.getClassLoader().getResourceAsStream(
                    default_config);
            Properties ps = new Properties();
            ps.load(is);
            ip = ps.getProperty("ftp.ip");
            username = ps.getProperty("ftp.username");
            password = ps.getProperty("ftp.password");
            remoteDir = ps.getProperty("ftp.remoteDir");
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
       /**
        * 
        * @param file 本地文件
        * @param path 上传到服务器目录
        * @param newfileName 新文件名
        * @return
        */
        @SuppressWarnings("unused")
        public static boolean ftpUpload(File file,String path,String newfileName){
            boolean flag=false;
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                if (fis == null){   
                      System.out.println("本地文件不存在");   
                } 
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("GBK");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置传输二进制文件 
                ftpClient.changeWorkingDirectory(path);
                ftpClient.storeFile(newfileName, fis);
                System.out.println("upload success!");
                flag=true;
            } catch (IOException e) {
                flag=false;
                System.out.println("upload File false!");   
                e.printStackTrace();
                throw new RuntimeException("FTP客户端出错!", e);
            } finally {
                IOUtils.closeQuietly(fis);
            }
            return flag;
        }
        
        /**
         * 连接ftp服务端
         * @创建人 
         * @创建时间 
         */
        public static void connectServer() {
            try {
                setParam();
                if(ftpClient == null || !ftpClient.isConnected()){ 
                    ftpClient = new FTPClient(); 
                    System.out.println("ftpIp:" + ip + "|userName:" + username + "|password:" + password);
                    ftpClient.connect(ip); 
                    ftpClient.login(username, password);
                    System.out.println("ftp login success!");
                    ftpClient.setDefaultPort(port);  
                }
                ftpClient.changeWorkingDirectory(remoteDir);
            } catch (Exception e) {
                e.printStackTrace();
                 throw new RuntimeException("打开FTP连接发生异常!", e); 
            }
        }
        /**
         * 关闭ftp服务连接
         * @创建人 
         * @创建时间 
         */
        public static void closeConnect() {
             try { 
                 ftpClient.disconnect(); 
             } catch (IOException e) { 
                 e.printStackTrace(); 
                 throw new RuntimeException("关闭FTP连接发生异常!", e); 
             } 
        }
           
           /**  
             * 进入到服务器的某个目录下  
             *  
             * @param directory  
         * @return 
             */  
           public static FTPFile[] changeWorkingDirectory(String directory) {   
               try {   
                   ftpClient.changeWorkingDirectory(directory);   
                   FTPFile[] files = ftpClient.listFiles(directory); 
                   return files;
                } catch (IOException ioe) {   
                   ioe.printStackTrace();   
               }
            return null;   
           }
           public static boolean makeDirectory(String path) throws IOException {
               if (!ftpClient.changeWorkingDirectory(path)) {
                   String[] paths=path.split("/");
                   String temp="";
                   for (int i = 0; i < paths.length; i++) {
                       if("".equals(paths[i]))continue;
                       if (!ftpClient.changeWorkingDirectory(temp+"/"+paths[i])) {
                             if (!ftpClient.makeDirectory(temp+"/"+paths[i])) {   
                                 System.out.println("创建文件目录【"+paths[i]+"】 失败!"); 
                                 return false;
                             } 
                        }
                       temp+="/"+paths[i];
                  }
               }
               return true;
           }
           public static void main(String[] args) {
               connectServer();
            /*   File file=new File("D:/test1.txt");
               try {
                makeDirectory("/ecp/member/item/id");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
               ftpUpload(file,"/ecp/member/item/id","test111.txt");*/
              FTPFile[] files=changeWorkingDirectory("");
               for (int i = 0; i < files.length; i++) {
                  System.out.print(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(files[i].getTimestamp().getTime())+"\n");
                }
               closeConnect();
           }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。