NodeJS를 사용하여 AWS S3에 여러 파일 업로드

Steven_

NodeJS를 사용하여 디렉터리 내의 모든 파일을 S3 버킷에 업로드하려고합니다. Key:필드에 대한 파일 경로 + 리터럴 문자열을 명시 적으로 제공하면 한 번에 하나의 파일을 업로드 할 수 있습니다 .

다음은 내가 사용중인 스크립트입니다.

var AWS = require('aws-sdk'),
    fs = require('fs');

// For dev purposes only
AWS.config.update({ accessKeyId: '...', secretAccessKey: '...' });

// reg ex to match
var re = /\.txt$/;

// ensure that this file is in the directory of the files you want to run the cronjob on

// ensure that this file is in the directory of the files you want to run the cronjob on
fs.readdir(".", function(err, files) {
    if (err) {
    console.log( "Could not list the directory.", err)
    process.exit( 1 )
    }


    var matches = files.filter( function(text) { return re.test(text) } )
    console.log("These are the files you have", matches)
    var numFiles = matches.length


    if ( numFiles ) {
        // Read in the file, convert it to base64, store to S3

        for( i = 0; i < numFiles; i++ ) {
            var fileName = matches[i]

            fs.readFile(fileName, function (err, data) {
                if (err) { throw err }

                // Buffer Pattern; how to handle buffers; straw, intake/outtake analogy
                var base64data = new Buffer(data, 'binary');


                var s3 = new AWS.S3()
                    s3.putObject({
                       'Bucket': 'noonebetterhaventakenthisbucketnname',
                        'Key': fileName,
                        'Body': base64data,
                        'ACL': 'public-read'
                     }, function (resp) {
                        console.log(arguments);
                        console.log('Successfully uploaded, ', fileName)
                    })
            })

        }

    }

})

S3에 업로드하려는 각 파일에 대해 다음 오류가 발생합니다.

These are the files you have [ 'test.txt', 'test2.txt' ]
{ '0': null,
  '1': { ETag: '"2cad20c19a8eb9bb11a9f76527aec9bc"' } }
Successfully uploaded,  test2.txt
{ '0': null,
  '1': { ETag: '"2cad20c19a8eb9bb11a9f76527aec9bc"' } }
Successfully uploaded,  test2.txt

편집 : 대신 키를 읽을 수 있도록 변수 이름을 사용하여 업데이트matches[i]

업로드 만하는 이유는 무엇 test2.txt이며 내 matches변수 내에서 각 파일을 업로드하려면 어떻게해야 합니까?

Steven_

솔루션에 도달하기 위해 nodejs에서 여러 파일을 비동기 적으로 읽고 캐싱하는 것을 참조했습니다 .

tl; dr 범위 문제-변수를 클로저로 래핑해야합니다. readFileand에 대한 함수를 만들고 s3.putObjectfor 루프 내에서 호출 하여이를 수행 할 수 있습니다 .

var AWS = require('aws-sdk'),
    fs = require('fs');

// For dev purposes only
AWS.config.update({ accessKeyId: '...', secretAccessKey: '...' });

var s3 = new AWS.S3()

function read(file) {
    fs.readFile(file, function (err, data) {
        if (err) { throw err }

        // Buffer Pattern; how to handle buffers; straw, intake/outtake analogy
        var base64data = new Buffer(data, 'binary');

        s3.putObject({
           'Bucket': 'noonebetterhaventakenthisbucketnname',
            'Key': file,
            'Body': base64data,
            'ACL': 'public-read'
         }, function (resp) {
            console.log(arguments);
            console.log('Successfully uploaded, ', file)
        })
    })
}

// reg ex to match
var re = /\.txt$/;

// ensure that this file is in the directory of the files you want to run the cronjob on
fs.readdir(".", function(err, files) {
    if (err) {
        console.log( "Could not list the directory.", err)
        process.exit( 1 )
    }

    var matches = files.filter( function(text) { return re.test(text) } )
    console.log("These are the files you have", matches)
    var numFiles = matches.length


    if ( numFiles ) {
        // Read in the file, convert it to base64, store to S3

        for( i = 0; i < numFiles; i++ ) {
            read(matches[i])
        }

    }

})

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

FFMPEG를 사용하여 파일을 변환하고 AWS S3 Nodejs에 업로드

각도에서 반응 양식을 사용하여 여러 파일 업로드

AWS EMR-올바른 암호화 키를 사용하여 S3에 쓰기

nodejs Express 4에서 단일 입력을 통해 여러 파일을 업로드하는 가장 좋은 방법은 무엇입니까?

Angular를 사용하여 zip 파일 다운로드

apache-commons-fileupload를 사용하여 Spring에서 파일을 업로드하는 동안 문제가 발생했습니다.

XML 파일 업데이트 및 XSLT를 사용하여 태그에 ID 할당

단일 file_uploader 레일로 여러 파일 업로드 4

Python을 사용하여 ftp 서버에 특정 형식으로 업로드 된 파일 표시

Microsoft Bot Framework를 사용하여 메시지에 카드 첨부 파일 추가

VBA를 사용하여 동적 폴더에 파일 복사

matplotlib를 사용하여 단일 PDF 페이지에 여러 플롯 저장

URL에서 AD를 사용하여 .desktop 파일 만들기

Live Sass 컴파일을 사용하여 scss를 CSS에 연결

S3 : 많은 수의 파일을 업로드하는 방법

Julia, Pluto.jl 및 PlutoUI.jl의 FilePicker 요소를 사용하여 업로드 된 CSV 파일을 읽는 방법

AWS를 사용하여 중국에서 데이터 송수신

웹 사이트 폴더에서 여러 JSON 파일 다운로드

Как убедиться, что сведения о корзине AWS S3 действительны или не используются Nodejs?

nodeJS AWS S3 загрузка данных неправильная кодировка

Загрузка нескольких файлов в AWS S3 с помощью NodeJS

NodeJs загрузить файл в AWS S3 - поврежденный файл

Ошибка при загрузке нескольких файлов из AWS S3 с помощью Nodejs

Удаление объекта AWS S3, Nodejs

작동하지 않는 ajax를 사용하여 PHP 파일에 변수 전달

빌드 / 릴리스 파이프 라인 작업을 사용하여 AzureDevOps git repo에서 개인 TFS 서버로 변경 사항 업로드

와일드 카드를 사용하여 경로에서 실제 경로 가져 오기

awk를 사용하여 두 파일을 비교할 때 파일 이름에 구문 오류가 있습니다.

3D 좌표를 사용하여 세 점 사이의 각도를 계산하는 파이썬 코드

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Резервное копирование / восстановление kafka и zookeeper

  3. 3

    Редактировать существующий файл Excel C # npoi

  4. 4

    Ipython использует% store magic для получения динамического имени

  5. 5

    Как получить список индексов всех значений NaN в массиве numpy?

  6. 6

    Почему бы не выдать ошибку ERROR в тесте Jasmine?

  7. 7

    Дженерики и потоки Java

  8. 8

    Как отфильтровать несколько столбцов в Qtableview?

  9. 9

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  10. 10

    Как изменить значок приложения для проекта libgdx android

  11. 11

    Thymeleaf не отображает значения в проекте Spring Boot

  12. 12

    Unity Проверить, включен ли Toggle

  13. 13

    Airflow не распознает мои настройки подключения S3

  14. 14

    Flutter: Unhandled Exception: FileSystemException: Creation failed, path = 'Directory: '' (OS Error: Read-only file system, errno = 30)

  15. 15

    Bogue étrange datetime.utcnow()

  16. 16

    На графике Matplotlib не отображается легенда

  17. 17

    Создание X509Certificate2 из ECC X509Certificate выдает исключение System.NotSupportedException в C #

  18. 18

    Как добавить фреймворк в файл в папке «Источники» Xcode Playground?

  19. 19

    Выполнение команд PowerShell в программе Java

  20. 20

    Статус HTTP 403 - ожидаемый токен CSRF не найден

  21. 21

    Инструмент для вставки данных, собранных в электронной таблице, в документ Word или PDF

популярныйтег

файл