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!');
    });
  • 相关阅读:
    CSS的扩展less和sass
    html5小游戏基础知识
    htm5拖放和画布
    htm5
    并查集模板
    二叉树的建树
    kmp的书写
    贪心算法
    容器
    POJ2442 优先队列
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7658985.html
Copyright © 2011-2022 走看看