Struts2+uploadify动态向后台传参数

前台代码 

<html>
  <head>
    <base href="<%=basePath%>">
    <title>文件上传</title>

	<link rel="stylesheet" type="text/css" href="uploadfy/uploadify.css"  />
    <script type="text/javascript" src="uploadfy/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="uploadfy/jquery.uploadify.js"></script>
    <script type="text/javascript" src="uploadfy/jquery.uploadify.min.js"></script>

	<script type="text/javascript">
		$(function() { 
            $("#files").uploadify({
            	 'multi': false,
                 'auto':false,
            	'fileObjName' : 'files',
                'swf': 'uploadfy/uploadify.swf',
                'uploader': 'upload.action',
                'multi': false,
                'overrideEvents' : ['onUploadProgress'],  
                'fileTypeDesc':'支持的格式:',
                'formData': {'ctrlid' : 1},
                //允许上传的文件后缀
                'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png',
                //上传文件的大小限制
                'fileSizeLimit':'3MB',
                //  'buttonImage':'upbutton.gif',
                //浏览按钮的宽度
                'width':'100',
                //浏览按钮的高度
                'height':'32',
                //上传数量 
                'queueSizeLimit' : 1,
                'onCancel':function(file) {
           			 alert('The file ' + file.name + ' was cancelled.');
      			  } ,
	            'onUploadSuccess':function(file, data, response){
	              	  var temp = eval("("+data+")");	//包数据解析为json 格式  
	              	  alert(temp.res.msg);
	            },
	     
	           'onUploadStart' : function(file) {
	            		$("#files").uploadify("settings", "formData", { 'ctrlid': $('#abc').val() });
	           },
               //在onUploadStart事件中,也就是上传之前,把参数写好传递到后台。

	            //返回一个错误,选择文件的时候触发
	            'onSelectError':function(file, errorCode, errorMsg){
	                switch(errorCode) {
	                    case -100:
	                        alert("上传的文件数量已经超出系统限制的"+$('#files').uploadify('settings','queueSizeLimit')+"个文件!");
	                        break;
	                    case -110:
	                        alert("文件 大小超出系统限制的"+$('#files').uploadify('settings','fileSizeLimit')+"大小!");
	                        break;
	                    case -120:
	                        alert("文件 大小异常!");
	                        break;
	                    case -130:
	                        alert("文件 类型不正确!");
	                        break;
	                }
	            },
	            //检测FLASH失败调用
	            'onFallback':function(){
	                alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
	            },
            });
        });  
		
	
		
    </script>
  </head>
  <body>
   		<div id="fileQueue"></div>  
	    <input type="file" name="files" id="files" />  
	    <input id="abc" type="text">
		<a href="javascript:$('#files').uploadify('upload');">确定上传</a>  
		
	    <div id="result"></div><!--显示结果--> 

  </body>
</html>

后台代码

package upload;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadFileAction extends ActionSupport{
//	private String getfile = null;
	 private File files = null;
	 private String title = null;
	 private String filesFileName = null;
	 private String filesContentType = null;
	 private String ctrlid;
	 private  JSONObject res;
	 
	public JSONObject getRes() {
		return res;
	}

	public void setRes(JSONObject res) {
		this.res = res;
	}

	public String getCtrlid() {
		return ctrlid;
	}

	public void setCtrlid(String ctrlid) {
		this.ctrlid = ctrlid;
	}

	public String getImageTimeName(String fileName){
		Date date=new Date();
		SimpleDateFormat sd=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
		return sd.format(date)+fileName.substring(fileName.lastIndexOf('.'));

	}
	 
	public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");

        String nowName=getImageTimeName(filesFileName);
        String realNamepath=realpath+"\\"+nowName;
        String relativePaht="images\\"+nowName;
        
        System.out.println(this.getCtrlid());
        
		try {
			System.out.println(nowName);
			System.out.println(realNamepath);
			System.out.println(relativePaht);
			
	

	        if (files != null) {
	            File savefile = new File(new File(realpath), nowName);
	            if (!savefile.getParentFile().exists()){
	            	  savefile.getParentFile().mkdirs();
	            }
	            FileUtils.copyFile(files, savefile);
	            
	    		Map<String, Object> map=new HashMap<String, Object>();
	            map.put("msg", "上伟成功!传递参数为:"+this.getCtrlid());
	       
	            this.setRes(JSONObject.fromObject(map));
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return SUCCESS;
	}


	public File getFiles() {
		return files;
	}

	public void setFiles(File files) {
		this.files = files;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getFilesFileName() {
		return filesFileName;
	}
	public void setFilesFileName(String filesFileName) {
		this.filesFileName = filesFileName;
	}
	public String getFilesContentType() {
		return filesContentType;
	}
	public void setFilesContentType(String filesContentType) {
		this.filesContentType = filesContentType;
	}
	
}

运行结果



注意事项

注意struts2的json返回结果配置
<package name="default" namespace="" extends="json-default">
        <action name="upload" class="upload.UploadFileAction">
        	<result type="json">
			</result>
        </action>
      </package>

注意JSON包的引入commons-beanutils-1.7.0.jar  commons-collections-3.2.jar commons-lang-2.4.jar commons-logging-1.1.jar ezmorph-1.0.4.jar json-lib-2.2.2-jdk15.jar


posted @ 2014-02-28 16:24  赵侠客  阅读(200)  评论(0编辑  收藏  举报