struts2+jquery+ajax实现上传&&校验实例

    一直以为ajax不能做上传,直到最近看了一些文章。需要引入AjaxFileUploaderV2.1.zip,下载链接:http://pan.baidu.com/s/1i3L7I2T

  代码和相关配置如下:

   js代码:

      

  <script>

        //ajax 无刷新上传文件
        function ajaxFileUpload() {
            //判断是否选择文件
            if($("#uploadFile").val() == null || $("#uploadFile").val()==""){
                alert("请选择需要上传的文件!");
                return;
            }
            //判断后缀名
            var filepath=$("#uploadFile").val();
            var extStart=filepath.lastIndexOf(".");
            var ext=filepath.substring(extStart,filepath.length).toUpperCase();
            if(".xls".toUpperCase() !=ext ){
                alert("只能上传Excel97-2003工作簿文件(xls)");
                return false;
            }
            //判断文件大小
            var file = $('#uploadFile').get(0).files[0];
            if (file) {
                var fileSize = 0;
                if (file.size > 2*1024 * 1024) {
                    alert("上传的文件大小不能超过2MB,请核对后重试!");
                    return false;
                }
            }
            $("#loading")
                    .ajaxStart(function () {
                        $(this).show();
                    })//开始上传文件时显示一个图片
                    .ajaxComplete(function () {
                        $(this).hide();
                    });//文件上传完成将图片隐藏起来

            $.ajaxFileUpload
            (
                    {
                        url: '<%=request.getContextPath()%>/server/doUploadAndInsert.action',//用于文件上传的服务器端请求地址
                        secureuri: false,//一般设置为false
                        fileElementId: 'uploadFile',//文件上传空间的id属性  <input type="file" id="file" name="file" />
                        dataType: 'json',//返回值类型 一般设置为json
                        success: function (result) {
                            var msgBean = result;
                            alert(msgBean.msgText);
                        }
                    });
            return false;

        }
    </script>

需要导入jquery星河ajaxfileupload.js,html代码:


<script src="<%=request.getContextPath()%>/plugin/jquery/jquery-1.7.2.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery-ui.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery.validate.min.js"></script>
<script src="<%=request.getContextPath()%>/plugin/jquery/jquery.metadata.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>

<
div id="page-content" class="clearfix" style="padding-top: 20"> <form id="myform" enctype="multipart/form-data" method="post" action="<%=request.getContextPath()%>/server/doUploadAndInsert.action"> <span style="font-size: 15px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; 选择文件<span style="color: #c91523">(*.xls格式)</span></span> <input id="uploadFile" type="file" style="font-size: 15px" label="浏览" name="uploadFile" accept="application/xls"></file> </form> <input type="button" style="margin: 0 0 20 370;font-size: 15px" class="btn btn-large btn-pink save-right" value="导入" onclick="return ajaxFileUpload();"/> </div>

struts2 配置:

    <package name="server" extends="interceptorPackge" namespace="/server">
        <action name="doUploadAndInsert" class="serverBaseInfoAction" method="doUploadAndInsert" >
            <result type="plainText" />
            <param name="savePath">uploadTemp</param>
        </action>
</package>

后端struts2 action代码:

 // 上传文件所需属性
    private String title;
    private File uploadFile;
    private String uploadFileContentType;
    private String SavePath;
    private String uploadFileFileName;
    Log log = LogFactory.getLog(this.getClass());public String doUploadAndInsert() throws Exception {
        PrintWriter out = null;
        MsgBean msg = new MsgBean();
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            out = response.getWriter();
            if(getUploadFile().length()>2097152){
                msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");
                msg.setMsgText(getUploadFileFileName()+"上传失败,文件太大。\r\n请不要上传超过2048KB的文件");
                out.write(JSON.toJSONString(msg));
                out.flush();
                return null;
            }
            //后缀名限制
            String suffixName = getUploadFileFileName().split("\\.")[1];
            if(!"xls".equalsIgnoreCase(suffixName)){
                msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");
                msg.setMsgText(getUploadFileFileName()+"上传失败,错误的文件格式!");
                out.write(JSON.toJSONString(msg));
                out.flush();
                return null;
            }

            UUID uuid = UUID.randomUUID();
            ServletContext servletContext = (ServletContext) ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
            String rootPath = servletContext.getRealPath("/");
            File folder = new File(rootPath + "\\" + getSavePath());
            if (!folder.exists()) {
                folder.mkdir();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(rootPath + "\\" + getSavePath() + "\\" + uuid+"_"+getUploadFileFileName());
            FileInputStream fileInputStream = new FileInputStream(getUploadFile());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, len);
            }
            fileInputStream.close();
            log.info("上传文件接收成功,文件存放全路径为:" + rootPath + "/" + uuid+"_"+getUploadFileFileName());     

        } catch (Exception e){
            msg.setMsgName("SysDefectAction_doDefUploadAndInsert_fail");
            msg.setMsgText(getUploadFileFileName()+"上传失败,"+e.getMessage());
            out.write(JSON.toJSONString(msg));
            out.flush();
        } finally{
            out.close();
            return null;
        }

    }

 

posted on 2015-06-08 11:49  babyblue  阅读(680)  评论(0编辑  收藏  举报