• Nodejs express 文件上传


    文件上传

    以下我们创建一个用于上传文件的表单,使用 POST 方法,表单 enctype 属性设置为 multipart/form-data。

    index.htm 文件代码修改如下:

    <html>
    <head>
    <title>文件上传表单</title>
    </head>
    <body>
    <h3>文件上传:</h3>
    选择一个文件上传: <br />
    <form action="/file_upload" method="post" enctype="multipart/form-data">
    <input type="file" name="image" size="50" />
    <br />
    <input type="submit" value="上传文件" />
    </form>
    </body>
    </html>

    server.js 文件代码修改如下:

    var express = require('express');
    var app = express();
    var fs = require("fs");
    
    var bodyParser = require('body-parser');
    var multer  = require('multer');
    
    app.use(express.static('public'));
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(multer({ dest: '/tmp/'}).array('image'));
    
    app.get('/index.htm', function (req, res) {
       res.sendFile( __dirname + "/" + "index.htm" );
    })
    
    app.post('/file_upload', function (req, res) {
    
       console.log(req.files[0]);  // 上传的文件信息
    
       var des_file = __dirname + "/" + req.files[0].originalname;
       fs.readFile( req.files[0].path, function (err, data) {
            fs.writeFile(des_file, data, function (err) {
             if( err ){
                  console.log( err );
             }else{
                   response = {
                       message:'File uploaded successfully', 
                       filename:req.files[0].originalname
                  };
              }
              console.log( response );
              res.end( JSON.stringify( response ) );
           });
       });
    })
    
    var server = app.listen(8081, function () {
    
      var host = server.address().address
      var port = server.address().port
    
      console.log("应用实例,访问地址为 http://%s:%s", host, port)
    
    })

    执行以上代码:

    $ node server.js 
    应用实例,访问地址为 http://0.0.0.0:8081

    浏览器访问 http://127.0.0.1:8081/index.htm

  • 相关阅读:
    Analysis Services features supported by SQL Server editions
    Azure DevOps to Azure AppServices
    Power BI For Competition
    Win10开机“提示语音”以及”随机播放音乐”
    Azure DevOps
    Allow Only Ajax Requests For An Action In ASP.NET Core
    Mobile CI/CD 101
    Configure SSL for SharePoint 2013
    AWS Step Function Serverless Applications
    Cordova Upload Images using File Transfer Plugin and .Net core WebAPI
  • 原文地址:https://www.cnblogs.com/xiaotaiyang/p/6090037.html
Copyright © 2020-2023  润新知