我的应用程序中有一个文件上传功能,无法上传大小超过10MB的JSON文件。如果用户上传文件> = 10 MB,我的应用应将其拆分为每个小于10 MB的较小JSON文件。此外,需要在新的低尺寸文件中维护正确的JSON对象。
有没有办法在Javascript或jQuery中执行此操作?
答案 0 :(得分:2)
我提出了这样的解决方案,没有任何特定的库。它确实使用了一些现代技术,但可能对您有用:
var openFile = function(event, callback) {
// get target input
var input = event.target;
// create an instance of filereader
var reader = new FileReader();
// define handler to get results
reader.onload = function(e){
var contents = e.target.result;
// use a promise maybe to make this neater
callback(contents);
};
// make sure you tell it to read as text
// also maybe add some validation on your input
// for correct types
reader.readAsText(input.files[0]);
};
var getChunks = function(str){
var chunks = [];
// not best at these things but this should be
// around 1mb max
var chunkSize = 1000000;
// while the chunk is less than the size indicated it goes
// into the same item of array
while (str) {
if (str.length < chunkSize) {
chunks.push(str);
break;
}
else {
chunks.push(str.substr(0, chunkSize));
str = str.substr(chunkSize);
}
}
return chunks;
}
var fileInput = document.querySelector('#jsonUpload');
fileInput.addEventListener('change', function(event){
openFile(event, function(str){
console.log(getChunks(str));
});
});
然后它会从:
读取json文件<input type='file' accept='*' id="jsonUpload">