form、iframe实现异步上传文件

转载自:http://blog.csdn.net/sunjing21/article/details/4779321

实现主要功能:

  • 页面提供一个上传图片的input file选择框,用于上传某一类型的数张图片
  • 每次选择完本地图片后,图片便异步存储到后台的文件夹中;
  • 并将路径信息存储到数据库中;
  • 页面上显示此图的缩略图,并在旁边显示一个删除标记,当点击时,将此图片从页面、数据库、后台的文件夹中删除
  • input file选择框清空,再点击用于上传下一张图片;



JSP页面编写如下:

<div>
    <form action="uploadWaiguanImage.do" id="waiguan_form" name="waiguan_form" 
          enctype="multipart/form-data" method="post" target="waiguan_hidden_frame">
        <span>
            <label>外观图</label>
            <img src="images/addImage.JPG">
            <input type="file" id="waiguan_add" name="waiguan_add"/>
        </span>
        <iframe name="waiguan_hidden_frame" id="waiguan_hidden_frame" style="display:none"></iframe>
        <c:forEach var="x" begin="1" end="3" step="1">
            <span>
                <img id="waiguan_image${x }" style="visibility:hidden" src="" width="100" alt="外观图${x }"/>
                <img id="waiguan_delete_image${x }" style="visibility:hidden;cursor: pointer" src="images/deleteImage.JPG"/>
            </span>
        </c:forEach>
    </form>                       
</div>

让form的target值为iframe,当form提交的时候,是异步iframe进行提交,不会影响页面的其他部分。 
c:forEach部分是首先隐藏了上传后显示的图片标签和删除标签(这里最大可以上传三张) 

相应的JS代码:采用的是JQuery写的,不过写的很啰嗦,有点像是原始JS操作 

/**
 * 页面加载时完成操作
 */
$(document).ready(function() {
// 设置上传外观图
    $("#waiguan_add").bind("change", function() {
        submitImage("waiguan", 3);
    });
}

/**
 * 上传图片
 * 
 * @param {}
 *            para_name 图片所属属性名
 * @param {}
 *            number 此类图片的总数量
 */
function submitImage(para_name, number) {
    var para_form = para_name + "_form";
    var para_image = para_name + "_image";

    // alert(para_image);

    for (var i = 1; i <= number; i++) {
        var srcValue = $("#" + para_image + i).attr("src");
        // alert(srcValue);
        // alert(srcValue.length);
        if (srcValue == "" || srcValue.length == 0) {
            // alert("break");
            break;
        }
    }

    if (i > number) {
        alert("已超过了此类图的上传最大限");
        // 重置上传按钮,使之为空
        resetUploadBotton(para_name + "_add");
    } else {

        $("#" + para_form).submit();
    }
}

/**
 * iframe上传外观图片的返回操作
 * 
 * @param {}
 *            msg 返回的图片所在地址
 */
function callbackWaiguan(msg) {

    if (msg != "error") {
        for (var i = 1; i <= 3; i++) {
            var srcValue = $("#waiguan_image" + i).attr("src");
            // alert(srcValue);
            if (srcValue == "" || srcValue.length == 0) {
                $("#waiguan_image" + i).attr("src", msg);
                $("#waiguan_image" + i).css("visibility", "visible");
                $("#waiguan_delete_image" + i).css("visibility", "visible");
                $("#waiguan_delete_image" + i).click(function() {

                    deleteImage("waiguan", i);

                });
                break;
            }
        }
    } else {
        alert("上传图片失败,后台程序出现问题!");
    }

    // 重置上传按钮,使之为空
    resetUploadBotton("waiguan_add");
}

/**
 * 删除某个图片时的异步操作
 * 
 * @param {}
 *            para_name
 * @param {}
 *            number
 */
function deleteImage(para_name, number) {
    var delete_image_id = para_name + "_image" + number;
    var imagePathName = $("#" + delete_image_id).attr("src");
    
    if (para_name == "waiguan") {

        $.get("deleteWaiguanImage.do", {
            deleteFile : imagePathName,
            t : Math.random()
        }, function(tag) {

            alert(tag);
            if (tag == "true") {
                $("#" + delete_image_id).attr("src", "");
                $("#" + delete_image_id).css("visibility", "hidden");
                $("#" + para_name + "_delete_image" + number).css("visibility",
                        "hidden");
            } else {
                alert("连接数据库失败,无法删除该图片!");
            }
        });
    }
}

/**
 * 重置上传按钮,使之为空
 * 
 * @param {}
 *            para_name_add
 */
function resetUploadBotton(para_name_add) {
    var form = document.createElement("form");
    var span = document.createElement("span");
    var para_image_file = document.getElementById(para_name_add);
    para_image_file.parentNode.insertBefore(span, para_image_file);
    form.appendChild(para_image_file);
    form.reset();
    span.parentNode.insertBefore(para_image_file, span);
    span.parentNode.removeChild(span);
    form.parentNode.removeChild(form);

}

上传图片采用的是定义的form的submit()提交,iframe的异步提交。 
返回操作将image的src的值,置为刚upload的图片在webroot中的位置,这样就能显示图片了。 
删除图片时,利用Ajax将要删除的图片路径发送到后台,进行删除,删除成功时,将页面html中image的src值置为空。


后台处理的方法如下: 

/**
     * 初始化SmartUpload类,用于上传文件
     * 
     * @param servlet
     * @return SmartUpload
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    public SmartUpload initSmartUpload(ActionServlet servlet)
            throws ServletException, IOException, SQLException {
        // 新建一个SmartUpload对象
        SmartUpload su = new SmartUpload();

        javax.servlet.jsp.PageContext pageContext = JspFactory
                .getDefaultFactory().getPageContext(servlet, request, response,
                        null, true, 8192, true);
        // 上传初始化
        su.initialize(pageContext);

        // 设定上传限制
        // 1.限制每个上传文件的最大长度。
        su.setMaxFileSize(10000000);

        // 2.限制总上传数据的长度。
        su.setTotalMaxFileSize(20000000);

        // 3.设定允许上传的文件
        su.setAllowedFilesList("jpg,gif,bmp,pcx,"
                + "tiff,jpeg,tga,exif,fpx,cad");

        // 4.设定禁止上传的文件
        su.setDeniedFilesList("exe,bat,jsp,htm,html");

        return su;
    }


/**
     * 异步上传外观图
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward uploadWaiguanImage(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        SeriesService seriesService = ServiceFactory.getSeriesService(request,
                response);

        String filePathName = null;

        boolean tag= true;
        try {
            //初始化SmartUpload对象
            SmartUpload su = seriesService.initSmartUpload(this.getServlet());
            //上传外观图,将文件存储在filePath中,遍历系列对象的外观图属性,将图片的位置存储在某一空的属性中 
            filePathName = "upload/" + seriesService.addWaiguanImage(su);

        } catch (Exception e) {
            e.printStackTrace();
            tag = false;
        }

        PrintWriter out = response.getWriter();
        if (tag == true) {
            out.println("<script>parent.callbackWaiguan('" + filePathName
                    + "')</script>");
        } else {
            out.println("<script>parent.callbackWaiguan('error')</script>");
        }

        return null;
    }

/**
     * 异步删除某个外观图
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward deleteWaiguanImage(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Integer seriesID = (Integer) request.getSession().getAttribute(
                "seriesID");
        String filePathName = (String) request.getParameter("deleteFile");

        SeriesService seriesService = ServiceFactory.getSeriesService(request,
                response);
        boolean tag = true;
        try {
            //从数据库中和文件路径中删除外观图
            tag = seriesService.deleteWaiguanImage(filePathName, seriesID);
        } catch (Exception e) {
            e.printStackTrace();
            tag = false;
        }

        PrintWriter out = response.getWriter();

        out.write(new Boolean(tag).toString());

        return null;
    }

这样,便完成了要实现的功能。

posted @ 2016-03-24 18:31  花语苑  阅读(584)  评论(0编辑  收藏  举报