繁体   English   中英

如何在 node.js 中上传图像文件?

[英]how to upload a image file in node.js?

 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)
   })

在节点中,我使用 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);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM