如何使用JSP/Servlet和Ajax将文件上传到服务器?

我正在创建一个JSP/Servlet Web应用程序,我希望通过Ajax将一个文件上传到servlet。我该怎么做呢?我正在使用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:

$(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");
        }
    });});

但是,它似乎没有发送文件内容。


LEATH
浏览 947回答 3
3回答

温温酱

说到点子上,如当前XMLHttpRequestjQuery使用的版本1是不可以使用JavaScript上传文件XMLHttpRequest..常见的解决方法是让JavaScript创建一个隐藏的<iframe>然后将表单提交给它,这样就会产生异步发生的印象。这也正是大多数jQuery文件上传插件所做的事情,例如jQuery表单插件&nbsp;(这里的例子).假设您的带有HTML表单的JSP是以这样的方式重写的,所以它不会坏的当客户端禁用JS(就像现在的.)时,如下所示:<form&nbsp;id="upload-form"&nbsp;class="upload-box"&nbsp;action="/Upload"&nbsp;method="post"&nbsp;enctype="multipart/form-data"> &nbsp;&nbsp;&nbsp;&nbsp;<input&nbsp;type="file"&nbsp;id="file"&nbsp;name="file1"&nbsp;/> &nbsp;&nbsp;&nbsp;&nbsp;<span&nbsp;id="upload-error"&nbsp;class="error">${uploadError}</span> &nbsp;&nbsp;&nbsp;&nbsp;<input&nbsp;type="submit"&nbsp;id="upload-button"&nbsp;value="upload"&nbsp;/></form>然后在jQuery表单插件的帮助下<script&nbsp;src="jquery.js"></script><script&nbsp;src="jquery.form.js"></script><script> &nbsp;&nbsp;&nbsp;&nbsp;$(function()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$('#upload-form').ajaxForm({ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;success:&nbsp;function(msg)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;alert("File&nbsp;has&nbsp;been&nbsp;uploaded&nbsp;successfully"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error:&nbsp;function(msg)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$("#upload-error").text("Couldn't&nbsp;upload&nbsp;file"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;&nbsp;&nbsp;});</script>至于servlet方面,这里不需要做任何特殊的事情。只需以与不使用Ajax时完全相同的方式实现它:如何使用JSP/Servlet将文件上传到服务器?如果X-Requested-With标头等于XMLHttpRequest或者不是,这样您就知道在客户机禁用JS的情况下,返回什么样的响应(到目前为止,禁用JS的主要是较旧的移动浏览器)。if&nbsp;("XMLHttpRequest".equals(request.getHeader("X-Requested-With")))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Return&nbsp;ajax&nbsp;response&nbsp;(e.g.&nbsp;write&nbsp;JSON&nbsp;or&nbsp;XML).}&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Return&nbsp;regular&nbsp;response&nbsp;(e.g.&nbsp;forward&nbsp;to&nbsp;JSP).}注意相对较新的XMLHttpRequest版本2能够使用新的File和FormDataAPI。另见HTML 5文件上传到Javaservlet和通过XMLHttpRequest将文件作为多部分发送.

慕莱坞森

这段代码对我来说很好:$('#fileUploader').on('change', uploadFile);function uploadFile(event)&nbsp; {&nbsp; &nbsp; &nbsp; event.stopPropagation();&nbsp;&nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp;&nbsp; &nbsp; &nbsp; var files = event.target.files;&nbsp;&nbsp; &nbsp; &nbsp; var data = new FormData();&nbsp; &nbsp; &nbsp; $.each(files, function(key, value)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.append(key, value);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; postFilesData(data);&nbsp;&nbsp; &nbsp;}&nbsp;&nbsp;function postFilesData(data)&nbsp; {&nbsp; &nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: 'yourUrl',&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; data: data,&nbsp; &nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json',&nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; success: function(data, textStatus, jqXHR)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //success&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function(jqXHR, textStatus, errorThrown)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('ERRORS: ' + textStatus);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; });&nbsp; }<form method="POST" enctype="multipart/form-data">&nbsp; <input type="file" name="file" id="fileUploader"/></form>
打开App,查看更多内容
随时随地看视频慕课网APP