如何在Koa中提供具有正确文件名和扩展名的文件?

问题描述 投票:1回答:1

我试图让用户使用Koa框架上传文件,将其存储在服务器端并允许它稍后再次下载。

使用koa-body上传文件时,文件上传时没有扩展名和随机字符串,如何将文件作为原始文件名和扩展名下载?

我在网上找到的所有在线例子都假设文件是​​用原始文件名上传的,这不是这里的情况。

const bodyparser = require('koa-body');

app.use(bodyparser({
  formidable: { uploadDir: './uploads' },
  multipart: true,
  basedir: './views',
  apps: app,
}));

文件正确上传到上传文件夹,但文件名和扩展名被删除并替换为随机字符串。 (例如upload_1d421fb33fcd1d43efc41352975358da)

router.post('/add', add);
router.get('/download/:filename', getDownload);

async function add(ctx) {
  const { body } = ctx.request;
  const thingfile = await ctx.request.files.thingfile;
  things.push({ name: body.thing, file: thingfile });

  ctx.redirect('/');
}

async function getDownload(ctx) {
  const {filename} = ctx.params;
  ctx.attachment(filename);
  await send(ctx, fname, { root: __dirname + '/uploads' });
}

我可以在调用URL / uploads / upload_1d421fb33fcd1d43efc41352975358da时下载该文件,但必须在客户端手动重命名该文件才能正常工作。

显然我错过了一些东西,或者我完全错了。我有点迷失在这里,所以提前感谢你指导我回到正轨!

koa
1个回答
0
投票

我正在使用koa身体并且可以获得实际名称

router.post('/stream', async (ctx) => {
  const { file } = ctx.request.files
  const { path, name } = file
  ctx.body = name
})

您可以将name属性添加到中间件配置中。

app.use(bodyparser({
  multipart: true,
  formidable: {

    keepExtensions: true,
    onFileBegin: (name, file) => {

      console.log(name)
      // get the file extension
      const ext = name.split('.').pop()
      console.log(ext)

    },
  },
}))

你可以在console.log中输入名称

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