码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-06-08 13:03:47      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

    一直以为ajax不能做上传,直到最近看了一些文章。代码和相关配置如下:

  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>

html代码:

<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;
        }

    }

 

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

标签:

原文地址:http://www.cnblogs.com/onmyway20xx/p/4560523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!