当前位置: 首页 > 工具软件 > score.js > 使用案例 >

Egg.js获取formData数据

公孙宏畅
2023-12-01

使用React进行post的请求时,Eggjs获取formData的数据

方法1:

使用formidable进行转换

// add()
const extraParams = await this.parse(this.ctx.req);
const {
      title,
      type,
      country,
      year,
      score,
      time
    } = extraParams && extraParams.fields;

// parse()
async parse(req) {
    const form = new formidable.IncomingForm();
    return new Promise((resolve, reject) => {
      form.parse(req, (err, fields, files) => {
        resolve({ fields, files });
      });
    });
  }

方法2:

使用multipart (获取数据,上传的(多个)文件)

async add() {
    const { ctx } = this;
    const { req } = ctx;
    // const stream = await this.ctx.getFileStream();单个文件使用
    const parts = ctx.multipart();
    let part;
    while ((part = await parts()) != null) {
      if (part.length) {
        console.log("field: " + part[0]);
        console.log("value: " + part[1]);
      } else {
        if (!part.filename) {
          continue;
        }
        console.log("field: " + part.fieldname);
        console.log("filename: " + part.filename);
        console.log("encoding: " + part.encoding);
        console.log("mime: " + part.mime);

        const writePath = path.resolve(
          "./src/",
          `${new Date().getTime() + part.filename}`
        );
        console.log(writePath);
        if (!fs.existsSync(writePath)) {
          fs.writeFileSync(writePath, "");
        }
        const writeStream = fs.createWriteStream(writePath);
        await part.pipe(writeStream);
      }
    }

    ctx.body = { status: "ok" };
  }

 

 类似资料: