Fastify中如何访问上传文件的文件路径

How to access the file path of uploaded files in fastify

当使用表单上传一些文件时,我可以在网络检查器的开发工具中看到,特别是在 view source.

中表单数据下的有效负载选项卡中

注意下面包含文件名,包括路径 twoItems/Screenshot... 它的这个路径 twoItems 我需要在 API 中访问但不能。

安全?呃,我为什么要这个? 它用于文档管理应用程序,用户不能在浏览器中创建文件夹然后添加文件。他们需要拖放文件的嵌套目录。

------WebKitFormBoundarydJ6knkAHgNW7SIF7
Content-Disposition: form-data; name="file"; filename="twoItems/Screenshot 2022-03-11 at 08.58.24.png"
Content-Type: image/png


------WebKitFormBoundarydJ6knkAHgNW7SIF7
Content-Disposition: form-data; name="file"; filename="twoItems/Screenshot 2022-03-11 at 08.58.08.png"
Content-Type: image/png

所以在 API 我有一个标准的 fastify API 运行

mport Fastify, { FastifyInstance, RouteShorthandOptions } from "fastify";
import { Server, IncomingMessage, ServerResponse } from "http";

const fs = require("fs");
const util = require("util");
const { pipeline } = require("stream");
const pump = util.promisify(pipeline);

const fastify: FastifyInstance = Fastify({});
fastify.register(require("fastify-multipart"));
fastify.register(require("fastify-cors"), {
  methods: ["GET", "PUT", "POST"],
});

const dir = "./files";
if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);
}

fastify.post("/upload", async (req: any, reply) => {
  console.log(req);
  const parts = await req.files();
  for await (const part of parts) {
    console.log(part); //---------------- LOG BELOW
    await pump(part.file, fs.createWriteStream(`./files/${part.filename}`));
  }
  reply.send();
});

const start = async () => {
  try {
    await fastify.listen(3001);
    const address = fastify.server.address();
    const port = typeof address === "string" ? address : address?.port;
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};
start();

我找不到如何访问每个项目的路径

当我注销时 part 我得到...

<ref *1> {
  fieldname: 'file',
  filename: 'Screenshot 2022-03-11 at 17.52.11.png',
  encoding: '7bit',
  mimetype: 'image/png',
  file: FileStream {
    _readableState: ReadableState {
      objectMode: false,
      highWaterMark: 16384,
      buffer: BufferList { head: [Object], tail: [Object], length: 4 },
      length: 208151,
      pipes: [],
      flowing: null,
      ended: false,
      endEmitted: false,
      reading: false,
      sync: false,
      needReadable: false,
      emittedReadable: false,
      readableListening: false,
      resumeScheduled: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      destroyed: false,
      errored: null,
      closed: false,
      closeEmitted: false,
      defaultEncoding: 'utf8',
      awaitDrainWriters: null,
      multiAwaitDrain: false,
      readingMore: false,
      dataEmitted: false,
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: null
    },
    _events: [Object: null prototype] {
      end: [Function (anonymous)],
      limit: [Function (anonymous)]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    bytesRead: 208151,
    truncated: false,
    _read: [Function (anonymous)],
    [Symbol(kCapture)]: false
  },
  fields: { file: [ [Object], [Object], [Object], [Circular *1] ] },
  _buf: null,
  toBuffer: [AsyncFunction: toBuffer]
}

这是未定义的...

console.log(part.path);

您需要设置服务生的选项:

fastify.register(require("fastify-multipart"), {
  preservePath: true
});

您可以在此处找到所有选项:https://github.com/fastify/busboy#busboy-methods