繁体   English   中英

Axios 发布大文件

[英]Axios post Large File

我正在尝试将大型 JSON 发布到我的数据库中,JSON 至少有 400.000 个对象。

如果我剪切文件并尝试发布 20.000 个对象,一切正常,所以问题应该是 JSON 的大小。

我已经将 JSON 分成 20 个块,我的想法是一次上传一个,但我很难让它工作。

这就是我正在使用的:

var rows = {};
Papa.parse(content, {
    header: false,
    delimiter: '|',
    worker: true,
    encoding: "utf16le",
    dynamicTyping: true,
    skipEmptyLines: true,
    complete: function(results) {
        rows = results.data;
        let obj = []
        for(var i=0; i < rows.length; i++){
            obj.push(rows[i])
        }

        let result = []

        for(let i in obj) {
            let temp = {}
            if(i > 0) {
                temp["id"] = obj[i][0]
                temp["name"] = obj[i][1]
                temp["tel"] = obj[i][2]
                temp["email"] = obj[i][3]
                temp["status"] = obj[i][5]
                
                result.push(temp)
            }
        }
        
        var array1 = result.map((e) => {
            return {
                id: e.id,
                name: e.name,
                email: e.email
            }
        })

        let chunked = []
        let size = 20000;

        Array.from({length: Math.ceil(array1.length / size)}, (val, i) => {
        chunked.push(array1.slice(i * size, i * size + size))
        })

        console.log(chunked); // at this point I have my array divided into chunks of 20000

        axios({
            url: 'url',
            method: 'post',
            data: chunked
          })
          .then(function (response) {
              // your action after success
              console.log(response);
          })
          .catch(function (error) {
             // your action on error successif (error.response) {
            console.log(error);
        
          });

您可以按以下方式一一发送。 假设您的后端能够接受数据格式。

    for(let i=0;i<chunked.length;i++){
          axios({
            url: 'url',
            method: 'post',
            data: chunked[i]
          })
          .then(function (response) {
              // your action after success
              console.log(response);
          })
          .catch(function (error) {
             // your action on error successif (error.response) {
            console.log(error);
        
          });
     }

或者一个现代的解决方案可能是使用Promise.all([])

let promiseArray = [];
for(let i=0;i<chunked.length;i++){
    promiseArray.push(axios({
       url: 'url',
       method: 'post',
       data: chunked[i]
    }))
}

Promise.all(promiseArray)
.then((responses) => {
  console.log(responses);   //Will return resolved/rejected promises in an array
})
.catch(error => { 
  console.error(error.response)
});;

你可以阅读更多关于Promise.all([]) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM