zoukankan      html  css  js  c++  java
  • [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!');
    });
  • 相关阅读:
    2019牛客多校 Round10
    2019牛客多校 Round9
    2019牛客多校 Round8
    2019牛客多校 Round7
    2019HDU多校 Round8
    2019HDU多校 Round7
    elasticsearch分词器
    elasticsearch的mapping
    elasticsearch批量操作
    elasticsearch元数据
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7658985.html
Copyright © 2011-2022 走看看