ajax上传文件 ajaxFileUpload

示例:

<script type="text/javascript">var basePath = '${pageContext.request.contextPath}/' ; </script>

<script language="JavaScript" src="${pageContext.request.contextPath}/script/jquery-1.4.2.js" type="text/javascript"></script>

 <SCRIPT type="text/javascript" src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></SCRIPT>

//上传单个文件(若要上传没有id的文件需要修改源码)
function uploadFile(id, url, data, successCallBack, errCallBack ,completeCallback){
 $.ajaxFileUpload({
     url: url ,
     secureuri: false ,
     fileElementId: id ,
     dataType: 'json' , //预期服务器返回的数据类型
     data: data ,
     success: successCallBack , 
     error: errCallBack,
     complete: completeCallback
 }) ; 
}
function addFile(){
 var id = '123456' ; 
 var f = $('<input type="file" name="image">') ; 
 f.appendTo('body') ; 
 f.attr('id', id) ; 
 f.bind('change', function(){
  uploadFile(id, basePath+'user/cerdentials/test.action', {'annex.remark':'abcccc'}, 
    function(rst){
     alert(rst.remark);
    },
    function(){},
    function(){
     $('#'+id).remove(); //以前的上传文件input已经不在了,当前页面有一个一样的上传文件input是克隆出来的
    }
  ) ; 
 }) ;  
}

 

<body>

<input type="button" onclick="addFile();" value="添加一个文件上传">

</body>

struts2 配置

<!--测试-->
        <action name="test" class="cn.com.xxx.action.imsusermgr.XxxAction" method="test">
            <result name="success" type="json">
                <param name="contentType">text/html</param> 
                <param name="root">annex</param>
                <param name="noCache">true</param>
                <param name="ignoreHierarchy">true</param>
            </result>
        </action>

action

//相关图片
    private File image ; 
    //上传的文件名
    private String imageFileName ; 
    //上传文件的类型
    private String imageContentType ; 
    private ImsAnnex annex ; //一个普通的javabean
public String test(){ System.out.println(annex.getRemark()); try { FileUtil.write(image, "d:/ff/abcc.gif") ; } catch (IOException e) { e.printStackTrace(); } annex = new ImsAnnex("123") ; annex.setRemark("asdfasdfsdf") ; return SUCCESS ; } public ImsAnnex getAnnex() { return annex; } public void setAnnex(ImsAnnex annex) { this.annex = annex; } get... set...

 

posted @ 2013-12-24 13:22  行-云  阅读(483)  评论(0编辑  收藏  举报