我有以下代码使用Html5在块中上传图像。
<!DOCTYPE html>
<form>
<div class="example">
#bytes/chunk:
<input id="numChunks" value="1048576" />
<input id="files" class="button" type="file" />
<div id="bars">
<span id="numofchunks">Num of chunks: </span>
<br />
<span id="message"></span>
</div>
</div>
</form>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
document.querySelector('input[type="file"]').addEventListener('change', function (e) {
var blob = this.files[0];
var BYTES_PER_CHUNK = (1024 * 1024) / 2; // 1MB chunk sizes.
var SIZE = blob.size;
$('#numofchunks').text($('#numofchunks').text() + SIZE / BYTES_PER_CHUNK);
var start = 10;
var end = BYTES_PER_CHUNK;
var counter = 1;
while (start < SIZE) {
upload(blob.slice(start, end), counter);
start = end;
end = start + BYTES_PER_CHUNK;
counter = counter + 1;
}
}, false);
});
function upload(blobOrFile, counter) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/basic/html5', true);
xhr.setRequestHeader("Content-Type", "image/jpeg");
// xhr.setRequestHeader("X-File-Name", blobOrFile.fileName);
xhr.onload = function () { $('#message').text($('#message').text() + counter + " ") };
var fd = new FormData();
fd.append("fileToUpload", blobOrFile);
xhr.send(fd);
};
</script>
这适用于所有浏览器,但它在我的Chrome中无效。在Chrome中,我没有收到服务器上的请求。在Chrome网络跟踪中,它始终将请求显示为待处理。
更新:我无法上传大文件(超过1mb)。无论我是否大块或大块的大小都没关系。如果图像大小超过1mb,则不会上传。
请参阅附带的错误屏幕截图
答案 0 :(得分:0)
试试这个
function(){
var blobs = [];
/*
* function that uploads a fragment of the file
*/
function uploadChunk(blob, fileName, fileType){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_chunks.cfm', false);
xhr.onload = function(e){
document.getElementById("messages").innerHTML += "Chunk of size " + blob.size + " uploaded successfully.<br/>";
}
xhr.setRequestHeader('X_FILE_NAME', fileName);
xhr.setRequestHeader('Content-Type', fileType)
document.getElementById("messages").innerHTML += "Uploading chunk of size " + blob.size + ".<br/>";
xhr.send(blob);
}
/*
* Invoke this function when the file is selected.
*/
document.querySelector('#userfile').addEventListener('change', function(){
var file = this.files[0];
var bytes_per_chunk = 1024 * 1024;
var start = 0;
var end = bytes_per_chunk;
var size = file.size;
while (start < size) {
//push the fragments to an array
blobs.push(file.slice(start, end));
start = end;
end = start + bytes_per_chunk;
}
//upload the fragment to the server
while (blob = blobs.shift()) {
uploadChunk(blob, file.name, file.type);
}
})
})();
答案 1 :(得分:0)