nodejs-tw / ama

Ask me anything!
MIT License
31 stars 1 forks source link

如何透過 Line Notify API,將圖片上傳到 Line Server #37

Closed mukiwu closed 3 years ago

mukiwu commented 3 years ago

目的

我想做一個 Line Notify 的機器人,希望可以在網頁上傳圖片後,在 Line 群組顯示這張圖片。

使用的工具

遇到的問題

透過前端,可以正常上傳圖片到專案資料夾裡 後端也有抓到圖片的資訊,但是就是沒有顯示在 LINE 群組

嘗試過的解法

參考來源:https://stackoverflow.com/questions/53038900/nodejs-axios-post-file-from-local-server-to-another-server

程式碼

下面附上我的程式碼以及我遇到的錯誤

程式碼

// 前端頁面
$(document).ready(function () {
    $("#uploadForm").submit(function (e) {
      e.preventDefault();
      let data = new FormData($('#uploadForm')[0]);
      data.append('message',$("#uploadMessage").val())
      $.ajax({
        url: '/t_sendMessage',
        type: 'POST',
        contentType: false,
        processData: false,
        cache: false,
        data: data,
        success: function (res) {
          alert('上傳成功');
          $("#uploadMessage").val();
          $("input").val("");
          console.log(res);
        },
        error: function (err) {
          console.log(err)
        }
      })
    });
  });
// app.js
app.post('/t_sendMessage', async function(req, res){
  upload(req, res, function(err){
    if(err) {
      console.log(err)
      return
    }
    const token = fs.readFileSync('./src/token.txt', 'utf8');
    const formData = {
      message: req.body.message,
      imageFile: req.file.path
    }
    lineNotify.testSendNotify(token, formData);
    res.send({msg:'上傳成功'});
  })
});
// lineNotify.js
async function testSendNotify(token, data) {
  const form = new FormData();
  const url = 'https://notify-api.line.me/api/notify';
  const request_config = {
    headers: {
      'Authorization': `Bearer ${token}`,
      "Content-Type": "multipart/form-data"
    }
  };

  form.append('message', data.message);
  form.append('imageFile', fs.createReadStream(data.imageFile));
  return axios.post(
    url, form, request_config).catch(error=>{console.log(error)});
}

錯誤

data: { status: 400, message: 'Failed to upload file.' } },
mukiwu commented 3 years ago

補上在 LineNotify.js 印出 form 的資料如下:

FormData {
  _overheadLength: 282,
  _valueLength: 4,
  _valuesToMeasure:
   [ ReadStream {
       _readableState: [ReadableState],
       readable: true,
       _events: [Object],
       _eventsCount: 3,
       _maxListeners: undefined,
       path:
        '/Users/muki/Documents/2.nodeJS/line-notify/public/storage/截圖 2020-11-09 08.48.30.png',
       fd: null,
       flags: 'r',
       mode: 438,
       start: undefined,
       end: Infinity,
       autoClose: true,
       pos: undefined,
       bytesRead: 0,
       closed: false,
       emit: [Function] } ],
  writable: false,
  readable: true,
  dataSize: 0,
  maxDataSize: 2097152,
  pauseStreams: true,
  _released: false,
  _streams:
   [ '----------------------------181194108314929746613113\r\nContent-Disposition: form-data; name="message"\r\n\r\n',
     'aaaa',
     [Function: bound ],
     '----------------------------181194108314929746613113\r\nContent-Disposition: form-data; name="imageFile"; filename="截圖 2020-11-09 08.48.30.png"\r\nContent-Type: image/png\r\n\r\n',
     DelayedStream {
       source: [ReadStream],
       dataSize: 0,
       maxDataSize: Infinity,
       pauseStream: true,
       _maxDataSizeExceeded: false,
       _released: false,
       _bufferedEvents: [Array],
       _events: [Object],
       _eventsCount: 1 },
     [Function: bound ] ],
  _currentStream: null,
  _insideLoop: false,
  _pendingNext: false,
  _boundary: '--------------------------181194108314929746613113' }