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!');
    });
  • 相关阅读:
    day16作业 后台管理
    华为园区网实验
    静态路由与思科的区别
    JUnit 两日游
    SQL语句学习积累·数据的操作
    僵固式思维 OR 成长式思维
    压测噩梦后的小感想
    跌跌撞撞的三年
    Linux命令累积
    LoadRunner 学习(基础一)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7658985.html
Copyright © 2011-2022 走看看