使用百度雲對象存儲BOSnodejs上傳文件

BOS上傳文件核心代碼

const config = {
    credentials: {
        ak: '',
        sk: ''
    }
};

let bucket = '';
let client = new BosClient(config);
let key = req.file.originalname;

client.putObjectFromFile(bucket, key, req.file.path, {
  'Content-Type': req.file.mimetype
}).then(response => {
    res.statusCode = 200;

}).catch(error => {
    console.log(error);
    res.statusCode = 500;
    res.send('error');
});

上傳接口服務代碼

const BosClient = require('@baiducloud/sdk').BosClient
const compression = require('compression')
app.use(compression());

const dirpath = path.resolve(path.join(__dirname, 'filedir'))
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, dirpath)
    },
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        cb(null, file.fieldname + "." + fileFormat[fileFormat.length - 1]);
    }
});

var upload = multer({
    storage: storage
})
app.post('/uploadImg', upload.single('upFile'), function (req, res) {
    console.log(req.file)
    if (req.file) {
    	// bos上傳代碼
    }
});

客戶端部分

使用FormData傳輸文件就行,取input的file對象的值即可。files[0]

  let formdata = new FormData();
  formdata.append('upFile', file);
  let xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://host:port/uploadImg', true);
  xhr.send(formdata);

  xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
              let fileName = xhr.response;
          } else {
              alert('上傳失敗稍後重試');
          }
      }
  }

總結

核心思想就是我們先用bos提供的sdk,傳入config,使用putObjectFromFile這個接口進行傳入文件,key就傳文件名,第三個參數就是文件的路徑,所以我們要先將客戶端傳來的文件進行存儲到本地。使用multer中間件。

參考鏈接

官方文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章