3 回答
TA贡献1752条经验 获得超4个赞
XMLHttpRequest
XMLHttpRequest
<iframe>
<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>
<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>
X-Requested-With
XMLHttpRequest
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
File
FormData
TA贡献1810条经验 获得超4个赞
这段代码对我来说很好:
$('#fileUploader').on('change', uploadFile);
function uploadFile(event)
{
event.stopPropagation();
event.preventDefault();
var files = event.target.files;
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
postFilesData(data);
}
function postFilesData(data)
{
$.ajax({
url: 'yourUrl',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
//success
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileUploader"/>
</form>
- 3 回答
- 0 关注
- 946 浏览
相关问题推荐
添加回答
举报