ajaxfileupload异步上传文件

来源:互联网 发布:java replace函数 正则 编辑:程序博客网 时间:2024/06/05 14:32

开发用的是SSH框架,奈何之前都是SSM

好了,不啰嗦,开始:

1 首先需要下载ajaxfileupload.js文件,百度一搜一堆


function uploadEnclosure(withdrawalsId){
 
        $("#uploadEnclosures").click();
        if(confirm("确认上传吗?")){
        //选择文件之后执行上传  
       
        var imgFile = $("#uploadEnclosures")[0].files[0]
        
            $.ajaxFileUpload({
                url:'/manager/pay-manager!saveUploadEnclosure.action',  
                secureuri:false,  
                fileElementId:'uploadEnclosures',
                dataType: 'json',
                data:{"id":withdrawalsId},    //fileImg:imgFile
                success: function (data, status) {  
                alert("上传成功!");
                var obj = $.parseJSON(data.replace(/<.*?>/ig,""));
                alert(obj.fileName);
                    $("#showImg").attr("src", "/WEB-INF/transferAccountsdetail/"+obj.fileName);
                },  
                error: function (data, status, e) {  
                    alert(e);  
                }  
            });  
 }   
 return true;  
}ajaxfileupload是不会解析返回的Json数据,所以一定要转成Json,不然返回的数据是

result:<pre style="word-wrap: break-word; white-space: pre-wrap;">{"flag":"true"}</pre><td >

  <a onclick="uploadEnclosure('${pageWithdrawals.id}')" href="#" id="upload">上传</a>&nbsp
  <img id="showImg" alt="" src="">
  <a onclick="#" href="#"  id="show">|&nbsp查看</a>
  <input type="file" style="display:none" id="uploadEnclosures" name="imgPath" accept="image/jpg,image/gif,image/png"></input>
</td>action中代码

private File imgPath;
private String imgPathFileName;
private HttpServletRequest request;public void saveUploadEnclosure() throws IOException, JSONException{

        //设置保存文件路径  
   String realPath =  ServletActionContext.getServletContext().getRealPath("WEB-INF/transferAccountsdetail");
        File file = new File(realPath);
        //测试此抽象路径名表示的文件或目录是否存在。若不存在,创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
        if(!file.exists())file.mkdirs();
        try {
            //保存文件
            FileUtils.copyFile(imgPath, new File(file,imgPathFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject obj = new JSONObject(); 
        obj.put("fileName", imgPathFileName);
        response.getWriter().print(obj.toJSONString());
        
}搞定~

原创粉丝点击