Node.js文件上传

Node.js express运用Multer完成文件上传
html部份

<div>
    <h3>文件上传:</h3>
    挑选一个文件上传: <br/>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="content"/>
        <br/>
        <input type="submit" value="上传文件"/>
    </form>
</div>

Node.js部份
装置multer:npm install multer –save

var express = require('express');
var app = express();
var fs = require('fs');
var multer = require('multer');
var upload = multer({dest: 'uploadFile/'});
//文件上传
app.post('/upload', upload.any(), function (req, res, next) {
    console.log(req.files[0]);  // 上传的文件信息
    var newFile = "./uploadFile/" + req.files[0].originalname;
    fs.readFile(req.files[0].path, function (err, data) {
        fs.writeFile(newFile, data, function (err) {
            if (err) {
                console.log("毛病:", err)
            } else {
                let response = {
                    message: '上传胜利',
                    filename: req.files[0].originalname
                };
                res.json(response);
            }
        });
    })
})
//图片加载,存储在uploadFile下的一切图片
app.get('/uploadFile/*', function (req, res) {
    res.sendFile( __dirname + "/" + req.url );
})

github地点:https://github.com/Rossy11/no…

    原文作者:Rossy1
    原文地址: https://segmentfault.com/a/1190000017169395
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞