【问题标题】:Fetching image from URL and uploading to another via POST in NodeJS从 URL 获取图像并通过 NodeJS 中的 POST 上传到另一个
【发布时间】:2019-12-07 02:08:48
【问题描述】:

在下面的 sn-p 中,我使用 node-fetchform-data 首先从远程 URL 检索图像文件,然后将其上传到 S3 存储桶(使用 aws-sdkmulter 在不同的脚本):

import fetch from 'node-fetch';
import fs from 'fs';
import FormData from 'form-data';

const form = new FormData();

const processProfileImg = (imageURL, userID) => {
  fetch(imageURL, userID)
    .then((response) => {
      const dest = fs.createWriteStream(`./temp/${userID}.jpg`);
      response.body.pipe(dest);
    })
    .then((dest) => {
      form.append('profileImage', fs.createReadStream(`./temp/${userID}.jpg`));
      fetch(`https://www.schandillia.com/upload/profile-image?userID=${userID}`, { method: 'POST', body: form })
        .then(response => response.json())
        .then(json => console.log(json));
    });
};

export default processProfileImg;

问题是,这涉及一个中间步骤,首先在检索文件时将文件存储在本地,然后再由form-data 函数将其拾取以进行 POST。有没有办法完全绕过这一步?我不想将文件保存在本地,我只想从远程 URL 中提取它并将其 POST 到上传路由而不创建本地文件。

更新:在稍微修改 sn-p 以实现 Fransebas(第一个答案)的建议并避免异​​步问题后,我遇到了一个新问题:本地保存的图像没问题,但是上传到 S3 的副本被部分截断了!

附加代码:处理POST上传的路由https://www.schandillia.com/upload/profile-image如下,当我尝试使用Postman上传文件时效果很好。

import dotenv from 'dotenv';
import express from 'express';
import aws from 'aws-sdk';
import multerS3 from 'multer-s3';
import multer from 'multer';
import path from 'path';

dotenv.config();
const router = express.Router();

// Set up S3
const s3 = new aws.S3({
  accessKeyId: process.env.IAM_ACCESS_KEY_ID,
  secretAccessKey: process.env.IAM_SECRET_ACCESS_KEY,
});

const checkFileType = (file, cb) => {
  // Allowed ext
  const filetypes = /jpeg|jpg/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);
  if (mimetype && extname) {
    return cb(null, true);
  }
  return cb('Error: JPEG Only!');
};

// Single Upload
const profileImgUpload = multer({
  storage: multerS3({
    s3,
    contentType: multerS3.AUTO_CONTENT_TYPE,
    bucket: `${process.env.S3_BUCKET_NAME}/w`,
    acl: 'public-read',
    key(req, file, cb) {
      cb(null, req.query.userID + path.extname(file.originalname));
    },
  }),
  limits: { fileSize: 2000000 }, // In bytes: 2000000 bytes = 2 MB
  fileFilter(req, file, cb) {
    checkFileType(file, cb);
  },
}).single('profileImage');

router.post('/profile-image', (req, res) => {
  profileImgUpload(req, res, (error) => {
    if (error) {
      console.log('errors', error);
      res.json({ error });
    } else if (req.file === undefined) {
      // If File not found
      console.log('Error: No File Selected!');
      res.json('Error: No File Selected');
    } else {
      // If Success
      const imageName = req.file.key;
      const imageLocation = req.file.location;
      // Save the file name into database into profile model
      res.json({
        image: imageName,
        location: imageLocation,
      });
    }
  });
});
// End of single profile upload

// We export the router so that the server.js file can pick it up
module.exports = router;

【问题讨论】:

标签: javascript node.js file post


【解决方案1】:

我没有使用那种发送数据的特定方式(我更喜欢 ajax),但是通过查看您的示例,我想您可以跳过在本地保存图像。如果您看到 fs.createReadStream 创建一个读取流。寻找从你得到的东西中创建读取流的方法。

另外,我认为您应该将发送代码放在then 中,这样您就不会遇到异步问题。例如,如果您发送数据的代码在then 内,那么您可以使用response.body 创建流。

您几乎得到它,但您仍在使用该文件,我认为您可以使用更像这样的东西存档它

import fetch from 'node-fetch';
import fs from 'fs';
import FormData from 'form-data';

const form = new FormData();

const processProfileImg = (imageURL, userID) => {
  fetch(imageURL, userID)
    .then((response) => {
      // Use response.body directly, it contains the image right?
      form.append('profileImage', response.body);
      fetch(`https://www.schandillia.com/upload/profile-image?userID=${userID}`, { method: 'POST', body: form })
        .then(response => response.json())
        .then(json => console.log(json));
    });
};

export default processProfileImg;

如果我正确理解fetch 的文档response.body 已经是一个流。

【讨论】:

  • 请看我的更新。我按照您的建议将上传代码包装成.then()。但是现在上传到 S3 的图片被部分截断了。
  • 抱歉,找不到任何可以满足 fileSteamFromBody 占位符的功能的东西。在这一点上,我不介意必须在本地保存文件的副本,只要上传顺利进行即可。连这么多都在苦苦挣扎。
  • 如果我正确理解了这个文档developer.mozilla.org/en-US/docs/Web/API/Streams_API/… body 已经是一个可读流,请看一下。
【解决方案2】:

这对我有用:

const axios = require('axios')
const FormData = require('form-data');

//Get image
let imageResponse = await axios({
    url: imageUrl,
    method: 'GET',
    responseType: 'arraybuffer'
})

//Create form data
const form = new FormData()
form.append('image', imageResponse.data, {
    contentType: 'image/jpeg',
    name: 'image',
    filename: 'imageFileName.jpg'
})

//Submit form
let result = await axios({
    url: serverUrl, 
    method: "POST",
    data: form, 
    headers: { "Content-Type": `multipart/form-data; boundary=${form._boundary}` }
})

【讨论】:

    猜你喜欢
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2021-01-19
    • 2020-12-22
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多