Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8886

『コピペOK』NodeでS3へ画像アップロード【2020】

$
0
0

まずは、ここからs3へのアクセスキーと、シークレットきーを取得してください。

S3 Bucketを作る

$ npm i --save aws-sdk
create-bucket.js
constAWS=require('aws-sdk');// Enter copied or downloaded access ID and secret key hereconstID='';constSECRET='';// The name of the bucket that you have createdconstBUCKET_NAME='test-bucket';//同じバケット名は作れない ユニーク必須consts3=newAWS.S3({accessKeyId:ID,secretAccessKey:SECRET});constparams={Bucket:BUCKET_NAME,CreateBucketConfiguration:{// アジアパシフィック (東京)LocationConstraint:"ap-northeast-1"}};s3.createBucket(params,function(err,data){if(err)console.log(err,err.stack);elseconsole.log('Bucket Created Successfully',data.Location);});

こんな感じ。で、実行

$ node create-bucket.js

S3で画像をアップする

uplode-bucket.js
constfs=require('fs');constAWS=require('aws-sdk');// Enter copied or downloaded access ID and secret key hereconstID='';constSECRET='';consts3=newAWS.S3({accessKeyId:ID,secretAccessKey:SECRET});constuploadFile=(fileName)=>{// Read content from the fileconstfileContent=fs.readFileSync(fileName);// Setting up S3 upload parametersconstparams={Bucket:"test-bucket",Key:'uniquename.jpg',// s3へ保存される名前 ユニーク必須Body:fileContent};// Uploading files to the buckets3.upload(params,function(err,data){if(err){throwerr;}console.log(`File uploaded successfully. ${data.Location}`);});};uploadFile('/Users/user-name/Desktop/test.png');//ここにファイルの実体を入れる

こんな感じ。で、実行

$nodeuplode-bucket.js

参考

https://stackabuse.com/uploading-files-to-aws-s3-with-node-js/


Viewing all articles
Browse latest Browse all 8886

Trending Articles