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!');
    });
  • 相关阅读:
    [LeetCode] 5. 最长回文子串 ☆☆☆(最长子串、动态规划)
    代码分层思考
    bash 字符串处理
    Shell脚本调试技术
    php fsockopen
    ajax 无刷新文件上传
    jquery validator
    详解机器学习中的熵、联合熵、条件熵、相对熵和交叉熵
    互信息
    条件熵
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7658985.html
Copyright © 2011-2022 走看看