11 javascript ajax jquery filereader arraybuffer
我正在开发一个函数,它将使用第三方API将数据写入块中的远程服务器.通过Stack Overflow的一些帮助,我能够实现这一目标,现在它正在按预期工作.问题是我只能得到一个16kb的块来写,因为我需要提前pos
写入下一个字节的位置.
初始写入很容易从0开始.由于我对此不熟悉,我不确定下一个pos
应该是16还是什么.如果有帮助,API调用writeFileChunk()
需要3个参数,即filepath(str),pos(int64)和data(base64编码的字符串).
reader.onload = function(evt)
{
// Get SERVER_ID from URL
var server_id = getUrlParameter('id');
$("#upload_status").text('Uploading File...');
$("#upload_progress").progressbar('value', 0);
var chunkSize = 16<<10;
var buffer = evt.target.result;
var fileSize = buffer.byteLength;
var segments = Math.ceil(fileSize / chunkSize); // How many segments do we need to divide into for upload
var count = 0;
// start the file upload
(function upload()
{
var segSize = Math.min(chunkSize, fileSize - count * chunkSize);
if (segSize > 0)
{
$("#upload_progress").progressbar('value', (count / segments));
var chunk = new Uint8Array(buffer, count++ * chunkSize, segSize); // get a chunk
var chunkEncoded = btoa(String.fromCharCode.apply(null, chunk));
// Send Chunk data to server
$.ajax({
type: "POST",
url: "filemanagerHandler.php",
data: { 'action': 'writeFileChunk', 'server_id': server_id, 'filepath': filepath, 'pos': 0, 'chunk': chunkEncoded },
dataType: 'json',
success: function(data)
{
console.log(data);
setTimeout(upload, 100);
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus); alert("Error: " + errorThrown); alert("Message: " + XMLHttpRequest.responseText);
}
});
}
else
{
$("#upload_status").text('Finished!');
$("#upload_progress").progressbar('value', 100);
getDirectoryListing(curDirectory);
}
})()
};
Run Code Online (Sandbox Code Playgroud)
小智 8
客户端文件的当前位置将由此行表示,或者更具体地说,是在增量前步骤中的第二个参数:
var chunk = new Uint8Array(buffer, count++ * chunkSize, segSize);
Run Code Online (Sandbox Code Playgroud)
但是,在这种情况下,它count++
可以在你重复使用之前使用advance(),所以如果你需要实际位置(如下所示pos
),你可以通过简单地将行重写为:
var pos = count++ * chunkSize; // here chunkSize = 16kb
var chunk = new Uint8Array(buffer, pos, segSize);
Run Code Online (Sandbox Code Playgroud)
这里每个位置更新将增加16kb,因为这是块大小.对于进度,然后计算pos / fileSize * 100
.这当然假设使用未编码的缓冲区大小.
唯一的特殊情况是最后一个块,但是当没有剩余的块要读取时,位置应该等于文件长度(fileSize
),所以它应该非常简单.
当ajax调用返回时,服务器应该具有相同的位置,除非出现问题(连接,写访问更改,磁盘已满等).
归档时间: |
|
查看次数: |
167 次 |
最近记录: |