Node express 使用 multer 上傳到 imgur 圖片儲存庫

Imgur Album 建立

imgur官網

  • 申請帳號
  • 登入 Imgur 網站
  • 右上角的使用者資訊下拉 images
這裡 接下來找到「All images」的下拉選單,裡面會有一個「New Album」 成功建立了一個 Album!

Imgur Album ID 取得

點一下使用者資訊下拉「gallery profile」

Posts => All

進入到 Album 之後看網址,我們只需要下方圖片紅框圈起來部分就好,那部分就是我們要找的 Album ID

註冊 Imgur 應用程式

Register an Application
Application name =>任意名字
Authorization type =>選 OAuth 2 authorization without a callback URL
Authorization callback URL =>https://imgur.com
Email=>聯絡的到你的信箱

獲得

Client ID:

Client secret:

如果不小心丟失 Client secret:
點一下「generate new secret」重新生成

取得 Refresh Token

${Client ID} =>放入申請的Client ID

1
https://api.imgur.com/oauth2/authorize?client_id=${Client ID}&response_type=token

按下Allow

取得 Refresh Token

1
https://imgur.com/#access_token=xxxxx&expires_in=xxxxxx&token_type=bearer&refresh_token=xxxxxxxxxxxxx&account_username=申請帳號&account_id=xxxxxxxxxxxx

安裝multer

1
npm install --save multer

設定 Multer

  • limits: 限制上傳檔案的大小
  • fileSize: 限制上傳檔案的大小 接受的單位為 bytes:1MB = 1000000 bytes(為 1MB)
  • fileFilter 限制接受的上傳格式
    其接受三個參數: request 物件、帶有上傳檔案資訊的file 物件、篩選完成後呼叫的cb 函式。
    cb() 是一個當篩選完成時被呼叫 Callback 函式,其接受兩個參數:(1)錯誤訊息 (2)說明是否接受該檔案的 Boolean 值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//載入multer
const multer = require('multer')

const upload = multer({
limits: {
fileSize: 1000000
},
fileFilter(req, file, cb) {

if (!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
return cb(new Error('圖片格式必須是png或jpg或jpeg格式'))
}
cb(undefined, true)
},
}).any();

安裝 imgur

1
npm install --save imgur@1.0.2

前置作業
在環境變數增加
IMGUR_EMAIL=xxxx@gmail.com
IMGUR_PASSWORD=xxxxxxx
IMGUR_CLIENTID=xxxxxx
IMGUR_CLIENT_SECRET=xxxxxxx
IMGUR_REFRESH_TOKEN=xxxxxx
IMGUR_ALBUM_ID=xxxxxx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const imgur = require('imgur')

router.post('/upload', (req, res, next) =>{
upload(req, res, () => {
// 設置憑證
imgur.setCredentials(
process.env.IMGUR_EMAIL,
process.env.IMGUR_PASSWORD,
process.env.IMGUR_CLIENTID
);
//上傳Base64
imgur.uploadBase64(
req.files[0].buffer.toString('base64'),
process.env.IMGUR_ALBUM_ID
)
.then((json) => {
res.send({ url: json.link });
})
.catch((err) => {
res.send(err.message);
});
})
});

打開Postman
method:Post
body=>form-data =>key(img) select :filed (選擇filed)=>上傳檔案

到imgur資料夾內檢查是否已經上傳到imgur