一个解决方案让我能够在不重新加载页面的情况下提交表单,不使用iframe或JSONP,虽然它在技术上可能被视为AJAX,但它没有相同的“跨源”问题。
function uploadFile() {
var file = document.getElementById('file').files[0];
var fd = new FormData();
fd.append('key', "${filename}");
fd.append("file",file);
xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open('POST', 'http://fake-bucket-name.s3-us-west-1.amazonaws.com/', true); //MUST BE LAST LINE BEFORE YOU SEND
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100/evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert("Done - " + evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file." + evt);
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
用一个简单的形式是这样的:
<form id="form1" enctype="multipart/form-data" method="post">
<div class="row">
<label for="file">Select a File to Upload</label><br>
<input type="file" name="file" id="file">
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="uploadFile()" value="Upload">
</div>
<div id="progressNumber"></div>
</form>
的uploadComplete(evt)
函数为回调。正如你所看到的,它也给你完成你可以显示你的用户的百分比。
注意:为此,您必须在您的S3帐户中设置正确的上传策略和CORS 策略。 - RonSper
你可以使用jquery setTimeOut函数在x秒后触发提交。没有AJAX我不认为这可能是页面不能重新加载。 – Vucko
如何提交表单?如果我们不知道您制作的是什么类型的请求,我们无法帮助您。您是否在表单上使用目标并将其提交到iframe? –
@Vucko,它可以通过使用隐藏的iframe作为表单目标(我之前已经完成了处理带有文件上传的表单)。 –