files.fileName.path 在强大中返回未定义

问题描述 投票:0回答:2

文件未保存在服务器上。 路径属性返回未定义。

const uploadProfile = (req, res) => {
  const form = formidable.IncomingForm();

  form.uploadDir = `./images`;
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return res.json("Formidable cannot parse the form");
    }

    console.log(files.image.path);
   res.json(files.image.path);
  });
};
javascript express file formidable
2个回答
0
投票
const uploadProfile = (req, res) => {

    const options = {
    uploadDir: `./images`,
    keepExtensions: true,
  };

  const form = new formidable.IncomingForm(options);

  form.parse(req, (err, fields, files) => {
    if (err) {
      return res.json("Formidable cannot parse the form");
    }

    const {filepath, originalFilename, newFilename, size , mimetype} = files.image
    //'image' is the fileName... files.fileName 
    console.log(newFilename, "...");
   
    res.json(newFilename);
  });
};

了解从 V1 迁移到 V2 或 V3 的信息


0
投票

我也有类似的问题:

const [afields, afiles] = await form.parse(req);

因为“afiles”下面的字段名称发生了变化:它可能是“files”,“image”,“upload”,...我不明白为什么...

我的解决方案是“解析”“afiles”对象:

        const uploadedFiles = [];
        
        const afilesValues = Object.values(afiles);
        const nbAfilesValues = afilesValues.length;
        for( let i=0; i<nbAfilesValues; i++){
            const value1 = afilesValues[i];

            if (typeof value1 == 'object' && value1.constructor.name == 'PersistentFile'){
                uploadedFiles.push(value1);
                continue;
            }
            
            if (typeof value1 == 'object' && value1.constructor.name == 'Array'){
                const nb2 = value1.length;
                for(let i2=0; i2<nb2; i2++){
                    const value2 = value1[i2];
                    
                    if (typeof value2 == 'object' && value2.constructor.name == 'PersistentFile'){
                        uploadedFiles.push(value2);
                        continue;
                    }
                }
                continue;
            }
        }

所以所有上传的文件都会在“uploadedFiles”数组中...

© www.soinside.com 2019 - 2024. All rights reserved.