【问题标题】:Have to wait for the second file upload request for the first one's data to send to AWS S3必须等待第二个文件上传请求才能将第一个数据发送到 AWS S3
【发布时间】:2021-02-11 07:14:31
【问题描述】:

非常感谢任何帮助!我花了很长时间寻找,但我没有找到像我这样的解决方案或问题......

我正在编写一个 Electron 应用程序,作为其中的一部分,有一个部分供用户拖放文件。然后,我将获取该文件并将其上传到 AWS S3。

我第一次拖放它进入我的函数但没有请求发送到 AWS S3,然后我再次拖放并发送预期的请求并保存文件但是它是第一个请求信息(名称,路径和正文),从那时起,当我拖放文件时,它每次都会发出请求,但总是使用前一个请求的信息。就像它后面的一个序列......

这是 s3 代码:

function submitNewFileS3(file, filepath) {
   const AWS = require('aws-sdk');

   AWS.config = new AWS.Config({
       accessKeyId: localStorage.getItem("accessKeyId"),
       secretAccessKey: localStorage.getItem("secretAccessKey"),
       region: 'eu-west-2'
   });

   var upload = new AWS.S3.ManagedUpload({
      params: {
          Bucket: 'sampe-bucket',
          Key: filepath, // File name you want to save as in S3
          Body: file
      }
   });
   return upload.promise();
}

我如何调用函数:

   var reader = new FileReader();

   reader.onload = function (e2) {
           // finished reading file data.
           finishUploading(e2.target.result);
    }

    function finishUploading(url) {

            // strip off the data: url prefix to get just the base64-encoded bytes
            var data;

            if (url.indexOf('data:image') > -1) {
                data = url.replace(/^data:image\/\w+;base64,/, "");
            } else if (url.indexOf('data:application') > -1) {
                data = url.replace(/^data:application\/\w+;base64,/, "");
            }

             //only firing after sencon upload

            var buf = Buffer.from(data, 'base64');

            var filePathS3 = directory + (fileName).replace(/\-/g, "_").replace(/ /g, "_");
            submitNewFileS3(buf, filePathS3).then(function (response) {
                console.log(response);
            }).catch(function (response) {
                console.log(response);
            });
     }

     reader.readAsDataURL(f); // start reading the file data.

有没有人有任何建议 - 我快疯了...我尝试了很多教程和解决方案,它们都有效...在第二次通话中...

在发出请求之前,我已经仔细检查了所有必需的数据。

非常感谢!

编辑 - 在发送要上传的文件之前,我的主要内容中发生的更多信息:

function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();

    var directory;

    if (e.target.id == 'drop_zone_overview') {
        //placed in general area, check which folders are showing to get dir
        console.log(e);

        //get whats visible
        var whatPath;
        $(".icon").each(function () {
           if (this.style.display != 'none') {
               whatPath = this.id;
           }
        });
        //pick one and check what root we're in
        var pathArray = whatPath.split('-');
        console.log(pathArray);

    } else if (e.target.id == 'drop_zone_individual') {
       //placed on top of folder, check dir
       directory = (e.target).getAttribute('data-targetfolder');
       console.log(directory);
    }

    var files = e.dataTransfer.files,
        folder;

    for (var i = 0, f; f = files[i]; i++) { // iterate in the files dropped
        if (!f.type && f.size % 4096 == 0) {
            // The file is a folder
            folder = true;
        } else {
            // The file is not a folder
            folder = false;
        }

        const fs = require('fs');

        console.log(f);

        var fileName = f.name;

        var reader = new FileReader();

        reader.onload = function (e2) {
            // finished reading file data.
            finishUploading(e2.target.result);
        }

        function finishUploading(url) {
            // strip off the data: url prefix to get just the base64-encoded bytes
            var data;

            if (url.indexOf('data:image') > -1) {
                data = url.replace(/^data:image\/\w+;base64,/, "");
            } else if (url.indexOf('data:application') > -1) {
                data = url.replace(/^data:application\/\w+;base64,/, "");
            }

            var buf = Buffer.from(data, 'base64');

            var filePathS3 = directory + (fileName).replace(/\-/g, "_").replace(/ /g, "_");
            submitNewFileS3(buf, filePathS3).then(function (response) {
                console.log(response);
            }).catch(function (response) {
                console.log(response);
            });

        }

        reader.readAsDataURL(f); // start reading the file data.

        uploadedFiles.push(f);
    }


    uploadedFiles.forEach(function (file) {
        var pathKey = directory + (file.name).replace(/\-/g, "_");
        pathKey = pathKey.replace(/ /g, "_").replace(/\//g, '-').replace(/\./g, '__');

        if ($('#' + pathKey).length) {
            //filename already exists in directory
            alert(file.name + ' already exists in folder ' + directory);
        } else {
            var displayDiv;

            if (file.type == 'image/png') {
                //image
                //add to directory
                displayDiv = '<img id="' + pathKey + '" class="fileInfo thumb file-type file-type-img" src="' + URL.createObjectURL(file) + '" ondblclick="preview_image(this)"/>'

            } else if (file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                //xlsx doc
                displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-xlsx" data-downloadLink="' + URL.createObjectURL(file) + '" ></div>';

            } else if (file.type == 'application/pdf') {
                //pdf doc
                displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-pdf" data-downloadLink="' + URL.createObjectURL(file) + '" ></div>';

            } else if (file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
                 //word doc
                displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-docx" data-downloadLink="' + URL.createObjectURL(file) + '" </div>';

                console.log('its a doc');

             } else if (file.type == 'application/x-zip-compressed') {
               //zip file doc

               displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-zip" data-downloadLink="' + URL.createObjectURL(file) + '" </div>';
           } else if (file.type == '') {
               //folder 
               console.log('what typep  is this~~~~~    ' + file.type);
               file.name = file.name + '/';
           }

           //save to folder array

            if (file.type == 'application/x-zip-compressed' || file.type == '') {
               var htmlTemplate = [
                   getHtml([
                    '<li id=' + pathKey.replace(/ /g, "_").replace(/\//g, '-').replace(/\./g, '__') + ' class="icon folderItems fileInfo thumb"  data-downloadLink="directory_' + pathKey + '" ondblclick="viewAlbum(this.id)" style="display:none">',
                    '<i id="drop_zone_individual" data-targetFolder="' + pathKey + '" class="folders fas fa-folder" style="font-size: 115px; color: rgb(13, 36, 60); cursor: pointer;"></i>',
                    '<div class="folderLabel" style="text-align:center">' + file.name + '</div>',
                    '</li>'
                    ])
                ];

                folders.push({
                    Key: directory + (file.name).replace(/\-/g, "_").replace(/ /g, "_"),
                    LastModified: file.lastModifiedDate,
                   Size: file.size,
                });

            } else {

                //append to ui file list
                var htmlTemplate = [
                    getHtml([
                    '<li id=' + pathKey + ' class="icon downloadableItem" style="display:none">',
                    '<span>',
                    '<div style="text-align:center">',
                    displayDiv,
                    '</div>',
                    '<div style="text-align:center">',
                    '<span>',
                    file.name,
                    '</span>',
                    '</div>',
                    '</span>',
                    '</li>'
                   ])
                ];


                //save to folder list
                folders.push({
                    Key: directory + (file.name).replace(/\-/g, "_").replace(/ /g, "_"),
                    LastModified: file.lastModifiedDate,
                    Size: file.size,
                    signedUrl: URL.createObjectURL(file)
                });
            }

            localStorage.setItem("s3Objects", JSON.stringify(folders));

            $('#photoAlbumViewerList').append(htmlTemplate);

            console.log(folders);

            $("#" + pathKey).click(function (e) {
            getAlbumInfo(this.id);

                if (e.shiftKey) {
                    if ($(this).hasClass('thumb')) {
                       $(this).removeClass('thumb').addClass('thumbChecked');
                       $(this).css("border", "2px solid #c32032");


                       // $(this).attr("data-downloadLink");
                       links.push($(this).attr("data-downloadLink"));

                       if (links.length != 0) {
                           $('.download').css("display", "block");
                       }
                   } else if ($(this).hasClass('thumbChecked')) {
                       $(this).removeClass('thumbChecked').addClass('thumb');
                       $(this).css("border", "2px solid white");
                       var itemtoRemove = $(this).attr('src');
                       links.splice($.inArray(itemtoRemove, links), 1);
                       console.log(links);

                       if (links.length == 0) {
                           $('.download').css("display", "none");
                       }
                    }
                }
            });
       }
   });

    uploadedFiles = [];
    e.target.classList.remove('drop_zone_hovered');
    $('#drop_zone_text').hide();
}

【问题讨论】:

  • 仅供参考 刚刚有人回来告诉我我没有兑现承诺 - 谢谢你回来了,我希望它是那么愚蠢!我试过了,还是不开心
  • 您能在submitNewFileS3 周围添加更多代码吗?你在使用循环吗?
  • @eol 就是这样。我想从小处着手,让它发挥作用,然后增加复杂性。一旦文件进入,我将其缓冲区和直接指定的路径发送到 submitNewFileS3 以立即上传。
  • @eol 什么都没有打印出来,在这两个帐户上它都进入了函数,但是在第一次调用时它会安静下来,然后它会返回预期的结果。有时第二次调用会返回第一次和第二次调用的数据。 Try/catch 第一次不返回任何内容,然后成功。 PS谢谢你的帮助
  • 拥有return await upload.promise().then(...) 肯定对您没有帮助。我希望这是 return upload.promise() 并且调用者会在您返回的 thenable 承诺上等待或使用 .then,但不能同时等待/然后。

标签: javascript node.js amazon-web-services amazon-s3 file-upload


【解决方案1】:

作为一个仅供参考 - 问题在于我重新初始化 AWS 和 S3 变量,因为我在启动开始时设置它并重新初始化它在重新建立连接时减慢了它的速度!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2023-04-11
    • 2021-01-04
    相关资源
    最近更新 更多