美文网首页
Node.js 上传图片

Node.js 上传图片

作者: lenbolan | 来源:发表于2021-02-01 16:32 被阅读0次
    1. 依赖
    • Express
    • Multer
    1. 通过 Express 构建项目后,在 ./routes/index.js 中添加代码,添加后如下:
    var express = require('express');
    var router = express.Router();
    var multer = require('multer');
    
    // 配置文件的存储位置
    var Storage = multer.diskStorage({
      destination: function(req, file, callback) {
        callback(null, './public/images');
      },
      filename: function(req, file, callback) {
        callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
      }
    });
    var upload = multer({
      storage: Storage
    }).single("imgUploader"); // Field name
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });
    
    // form action
    router.post("/api/upload", function(req, res) {
      upload(req, res, function(err) {
        if (err) {
          console.log(err);
          return res.end("Something went wrong!");
        }
        return res.end("File uploaded successfully!");
      });
    });
    
    module.exports = router;
    
    
    1. 修改 views/index.jade 后如下:
    extends layout
    
    block content
      h1= title
      p Welcome to #{title}
      form(action="/api/upload", method="post", enctype="multipart/form-data")
        input(type="file", name="imgUploader", multipart)
        input(type="submit", name="submit", value="Upload")
    
    1. 运行后界面如下:


      截屏2021-02-01 下午4.30.19.png

      选择图片上传测试成功即完成

    相关文章

      网友评论

          本文标题:Node.js 上传图片

          本文链接:https://www.haomeiwen.com/subject/hetstltx.html