【问题标题】:how to upload a image file in node.js?如何在 node.js 中上传图像文件?
【发布时间】:2020-09-26 09:46:02
【问题描述】:
 var title="this is title";
  var content="this is content";
  const config = { headers: {'Accept': 'application/json', 'Content-Type': 'multipart/form-data' } };
  const form = new FormData()
  let file =event.target.files[0]
  form.append('file', file)
 form.append('title', title)
   form.append('content', content)`enter code here`
Axios.post("http://localhost:3001/article/get/123", form,config ).then((res)=>{
     console.log(res.data)
   })

【问题讨论】:

  • 欢迎来到 Stack Overflow。请按照建议添加您的搜索/研究工作的简短描述、代码、错误。
  • 这能回答你的问题吗? How to upload files using React?

标签: node.js angularjs reactjs express multipartform-data


【解决方案1】:

在节点中我使用 multer 上传图片或其他任何东西。

以下是我用作中间件的上传代码。

const util = require("util");
const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({ 
    destination: function (req, file, cb) {
        cb(null, "./Uploads") // folder path where to upload
    }, 
    filename: function (req, file, cb) { 
      cb(null, file.originalname + "-" + Date.now() + path.extname(file.originalname))
    } 
  });

const maxSize = 1 * 20000 * 20000; // file size validation

const uploadFiles = multer({ storage: storage, limits: { fileSize: maxSize } }).array("myfiles", 10); // key name should be myfiles in postman while upload

const uploadFilesMiddleware = util.promisify(uploadFiles);

module.exports = uploadFilesMiddleware;

以下是我在控制器中创建的用于上传和文件检查的功能。

fileUpload = async (req, res) => {
  try {
        let userCode = req.headers.user_code;
        await upload(req, res);
        if (req.files.length <= 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Kindly select a file to upload..!!', true));
        }
        let response = [];
        for (const element of req.files) {
            let data =  await service.addFileData(element, userCode);
            response.push(data); // for file path to be stored in database
        }
        if (response && response.length > 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators(response, httpStatusCode.OK, 'File uploaded sucessfully..!!', false));
        } else {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Failed to upload file kindly try later..!!', true));
        }
      } catch (error) {
            logger.warn(`Error while fetch post data. Error: %j %s`, error, error)
            return res.status(httpStatusCode.INTERNAL_SERVER_ERROR).send(responseGenerators({}, httpStatusCode.INTERNAL_SERVER_ERROR, 'Error while uploading file data', true))
        }
    }

路线会这样走。

router.post('/upload/file', fileUploadController.fileUpload);

并确保在文件上传时在邮递员中保持与在中间件中相同的名称。

【讨论】:

    【解决方案2】:

    以上代码在 react.js 中。我想在 node.js 中做同样的工作,文件将从公用文件夹上传。主要问题是如何以我们在前端 event.target.files[0]

    中的格式上传图像文件

    【讨论】:

    • 基本上我想将图像文件从节点服务器发送到本地python服务器。我的图像文件在公共文件夹中。那么我如何将图像文件发送到 python 服务器
    • 我们控制台 event.target.files[0] 你知道的结果是什么。我希望从后端文件到控制台的结果
    猜你喜欢
    • 2013-07-16
    • 2020-06-12
    • 2013-05-22
    • 2020-07-10
    • 2015-12-09
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    相关资源
    最近更新 更多