2015-04-28 54 views
2

我在我的应用程序中有一个文件上传功能,它无法上传超过10MB大小的JSON文件。如果用户上传文件大于等于10 MB,我的应用程序应将其分割成小于10MB的较小JSON文件。此外,正确的JSON对象需要维护在新的小尺寸文件中。将大型JSON拆分为Javascript/jQuery中的较小部分

有没有办法在Javascript或jQuery中做到这一点?

+0

压缩然后解? –

+0

有大块上传,你可以使用...看看[plupload](http://www.plupload.com/)例如。它也有多种语言的服务器端代码 – charlietfl

+0

解析JSON,分成多个部分,将每个部分串起来,上传。 – dandavis

回答

1

我提出这样的解决方案,没有任何特定的库。它使用一些现代技术,但也许对你有用:

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"> 

Link to the fiddle