我正在创建一个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"); } }); });
解决方法
到目前为止,由jQuery使用的当前XMLHttpRequest版本1,无法使用JavaScript通过XMLHttpRequest上传文件.常见的解决方法是让JavaScript创建一个隐藏的< iframe>并将表单提交给它,以便创建其异步发生的展示.这也正是大多数jQuery文件上传插件正在做的事情,如
jQuery Form plugin(
example here).
假设您的HTML表单的JSP以这样的方式重写,以便当客户端禁用JS(如现在…)时不会损坏,如下所示:
<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 Form插件只是一个问题
<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:How to upload files to server using JSP/Servlet?时的方式完全相同
如果X-Requested-With标头等于XMLHttpRequest,那么您只需要对servlet进行额外的检查,以便您了解客户端禁用JS的情况下如何返回什么样的响应(至此,大多数是早期的移动浏览器,禁用JS).
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). }
请注意,相对较新的XMLHttpRequest版本2能够使用新的File和FormData API发送选定的文件.另见HTML5 File Upload to Java Servlet和sending a file as multipart through xmlHttpRequest.