[Express] Upload Files with Express

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Express] Upload Files with Express相关的知识,希望对你有一定的参考价值。

In this lesson we create a new Express web server app for handling file uploads and persisting them to the filesystem. We will walk through using the express-fileupload middleware module from npm to process file uploads, and then use the Express static middleware to serve the uploaded file as a static asset.

 

const path = require(‘path‘);
const express = require(‘express‘);
const fileUpload = require(‘express-fileupload‘);
const app = express();

app.use(fileUpload());
app.use(‘/uploads‘, express.static(path.join(__dirname, ‘uploads‘)));

app.get(‘/‘, (req, res) => {
  res.send(`
    <form action="/upload" enctype="multipart/form-data" method="post">
      <input type="file" name="foo" /><br /><br />
      <input type="submit" value="Upload" />
    </form>
  `);
});

app.post(‘/upload‘, (req, res) => {
  if (!req.files) return res.status(400).send(‘No files were uploaded!‘);

  const { foo } = req.files;
  const uploadTo = `uploads/${foo.name}`;

  foo.mv(uploadTo, (err) => {
    if (err) return res.status(500).send(err);

    res.send(`File uploaded to <a href="${uploadTo}">${uploadTo}</a>`);
  });
});

app.listen(8080, () => {
  console.log(‘Server listening on port 8080!‘);
});

 

以上是关于[Express] Upload Files with Express的主要内容,如果未能解决你的问题,请参考以下文章

使用 NodeJS 的 Slack API (files.upload)

upload request files

javascript #upload #nodejs #multer #express

带有 express.js 的 jquery-file-upload-middleware:如何移动文件和添加水印?

Notes | GitHub Upload Large Files

上传多张图片时 ,对 $_FILES 的处理. upload