如何使用JSP / Servlet和Ajax来上传文件到服务器? [英] How to upload files to server using JSP/Servlet and Ajax?

查看:282
本文介绍了如何使用JSP / Servlet和Ajax来上传文件到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个JSP / Servlet的web应用,我想将文件上传到通过Ajax一个Servlet。我怎么会去这样做呢?我使用jQuery。

I'm creating a JSP/Servlet webapplication and I'd like to upload a file to a Servlet via Ajax. How would I go on doing this? I'm using jQuery.

我已经做了迄今:

<form class="upload-box">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error" />
    <input type="submit" id="upload-button" value="upload" />
</form>

通过这个jQuery的:

With this jQuery:

$(document).on("#upload-button", "click", function() {
    $.ajax({
        type: "POST",
        url: "/Upload",
        async: true,
        data: $(".upload-box").serialize(),
        contentType: "multipart/form-data",
        processData: false,
        success: function(msg) {
            alert("File has been uploaded successfully");
        },
        error:function(msg) {
            $("#upload-error").html("Couldn't upload file");
        }
    });
});

然而,它不会出现要发送的文件内容。

However, it doesn't appear to send the file contents.

推荐答案

要的一点,作为电流 XMLHtt prequest 第1版所使用的jQuery的,它的不可以可以通过 XMLHtt prequest 上传使用JavaScript文件。共同的解决办法是让JavaScript的创建一个隐藏的&LT; IFRAME&GT; 和表单提交给它,而不是使得IM pression创建,它是异步。这也正是大多数的jQuery文件上传插件都在做,如的jQuery插件形式(<一HREF =htt​​p://jquery.malsup.com/form/#file-upload相对=nofollow>例如这里)。

To the point, as of the current XMLHttpRequest version 1 as used by jQuery, it is not possible to upload files using JavaScript through XMLHttpRequest. The common workaround is to let JavaScript create a hidden <iframe> and submit the form to it instead so that the impression is created that it happens asynchronously. That's also exactly what the majority of the jQuery file upload plugins are doing such as jQuery Form plugin (example here).

假设你的JSP与HTML表单被改写成这样的方式,以便它不是当客户有JS禁用(因为你现在有...),如下图所示:

Assuming that your JSP with the HTML form is rewritten in such way so that it's not broken when the client has JS disabled (as you have now...), like below:

<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error">${uploadError}</span>
    <input type="submit" id="upload-button" value="upload" />
</form>

然后,它的使用jQuery形式的帮助插件的只是一个问题

Then it's with help of jQuery Form plugin just a matter of

<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
    $(function() {
        $('#upload-form').ajaxForm({
            success: function(msg) {
                alert("File has been uploaded successfully");
            },
            error: function(msg) {
                $("#upload-error").text("Couldn't upload file");
            }
        });
    });
</script>

至于servlet的身边,没有什么特别的东西需要在这里完成。只是实现它完全相同的方式,你会在不使用Ajax做的:<一href="http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet/2424824#2424824">How将文件上传到使用JSP / Servlet的服务器?

您只需要在当 X-要求 - 以头等于 XMLHtt prequest 与否,让你懂得回报的客户端有JS禁用的情况下,什么样的反应(截至目前,它大多是具有JS禁用旧的移动浏览器)。

You'll only need an additional check in the servlet if the X-Requested-With header equals to XMLHttpRequest or not, so that you know how what kind of response to return for the case that the client has JS disabled (as of now, it are mostly the older mobile browsers which have JS disabled).

if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
    // Return ajax response (e.g. write JSON or XML).
} else {
    // Return regular response (e.g. forward to JSP).
}

需要注意的是相对较新的 XMLHtt prequest 2版能够使用新的发送所选文件的文件 FORMDATA 的API。另请参见<一个href="http://stackoverflow.com/questions/7114087/html5-file-upload-to-java-servlet/7136219#7136219">HTML5文件上传的Java Servlet 和<一href="http://stackoverflow.com/questions/9395911/sending-a-file-as-multipart-through-xmlhtt$p$pquest/9397172#9397172">sending该文件为多部分通过xmlHtt prequest 。

Note that the relatively new XMLHttpRequest version 2 is capable of sending a selected file using the new File and FormData APIs. See also HTML5 File Upload to Java Servlet and sending a file as multipart through xmlHttpRequest.

这篇关于如何使用JSP / Servlet和Ajax来上传文件到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆