Prior to the upcoming version of XMLHttpRequest version 2, you cannot upload a file using Ajax.
Most modern users downloaded by Ajax use <iframe>hack. It uses JS code to create the invisible <iframe>where the form was copied and submitted synchronously. The parent page will remain unchanged and looks as if it was running asynchronously.
, JS-, / HTML DOM, jQuery. , jQuery-form plugin. <iframe> hack. ,
<script src="jquery.js"></script>
<script src="jquery-form.js"></script>
<script>
$(document).ready(function() {
$('#formid').ajaxForm(function(data) {
$('#result').text(data.result);
});
});
</script>
...
<form id="formid" action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
<div id="result"></div>
servlet, , Servlet 3.0 HttpServletRequest#getParts(), Apache Commons FileUpload ().
JSON .
Map<String, Object> data = new HashMap<String, Object>();
data.put("result", "Upload successful!");
response.setContentType("application/json");
resposne.setCharacterEncoding("UTF-8");
resposne.getWriter().write(new Gson().toJson(data));
Ajax-Servlet-JSON .