快递获取图片并发送到imgur

Express get picture and send to imgur

我正在使用 express 和 nodejs, 我想使用 imgur 来托管图片。 我有我的访问令牌,我需要请求这个端点:“https://api.imgur.com/3/upload” 使用 header : headers: {'Authorization': "bearer " + config.access_token_imgur, 'content-type': 'multipart/form-data'} 使用给定的图片。

要做到这一点,第一个问题是处理图片:这是 multipart 而 bodyparser 不能。 我试过 multer,但它总是保存图片,我只想得到它,然后 post 它到端点,所以, 我的目标是:

    router.post("/upload",upload.single('file'), async (req,res)=>{ 
  if(req.file){
    var headers = {
        headers: {"Authorization" : `Bearer ${config.access_token_imgur}`, 'content-type': 'multipart/form-data'}
    };
    var formData = new FormData();
    //formData.append("image", req.file);
    axios.post('https://api.imgur.com/3/upload', formData, headers).then((res)=>{
        console.log(res);
        console.log(res.body);
        console.log(res.data);
    }).catch((error)=>{
        console.log(error);
    })

    //must get a picture from the parameters (how to handle ? )
    //send it to https://api.imgur.com/3/upload with headers with post method
    //handle response
  }else{
      res.status(500).json({success: false})
  }

})

如您所见,我尝试使用 multer,但我认为这不是好的答案: 图片不保存怎么处理? (多部分),并将其发送到端点? (axios,请求,...) 谢谢

你说得对,bodyParser 不会帮助你处理多部分数据。

解决方案 1:

您仍然可以使用 multer 进行处理,但使用不同的存储引擎。例如,您可以使用 MemoryStorage,它只会将正在处理的文件缓存在内存中,而不会将它们实际写入磁盘。

解决方案 2:

如果您想完全跳过图像处理,您可以使用类似以下代码的方式将请求转发给第 3 方服务:

const request = require('request')
...

router.post('/upload', (req,res, next) => { 
  const forwardReqConfig = {
    url: 'https://api.imgur.com/3/upload',
    headers: {
      'Authorization': `bearer ${config.access_token_imgur}`,
      'Content-Type': 'multipart/form-data'
    }
  };
  req.pipe(request.post(forwardReqConfig)).pipe(res)
})

因为表达 req object inherits from nodejs request object it is also a stream. The same applies for res object as well. You can pipe req stream into the stream created by the request lib 然后将来自第 3 方服务的响应通过管道返回到您的 API.

的资源中

希望对您有所帮助。

我做到了:

 router.post('/upload', (req, res, next)=> { // --> must verify file type
    var busboy = new Busboy({ 
      headers: req.headers,
      limits: {
        fileSize: 1000000 * 200, //limit to 200mb because imgur's limit, and 1gb is buffer's limit --> must pass on aws s3 if needed - limit in byte
        files: 1,
      }
    });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        if(fieldname == 'image') {
            // the buffer
            file.fileRead = []; //------------need convert to gif !!----------- ------------------------------------------------
            file.on('data', function(data) {
                // add to the buffer as data comes in
                this.fileRead.push(data);
            });
            file.on('limit', ()=>{
              res.status(500).json({success: false, message: "file too big ! Musn't cross the line of 200mo ! We'll soon reduce this limit"})
            })
            file.on('end', function() {
                // create a buffer
                var finalBuffer = Buffer.concat(this.fileRead); 
                upload = uploadpicture(finalBuffer, mimetype).then((response)=>{ //success request
                  console.log(response);
                  res.status(200).json({success: true, message: "Successfully uploaded !", url: response.data.link});
                },(err)=>{ //error
                  console.log(err);
                  res.status(500).json({success: false, message: "Error happenned while uploading !"});
                }).catch((err)=>{
                  console.log(err);
                  res.status(500).json({success: false, message: "Error happenned while uploading !"});
                });
            })
        }
    });
/*    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
        console.log('field');
    });*/
    busboy.on('finish', function() {
        //busboy finished
    });
    req.pipe(busboy);
});