美文网首页
nodejs--file文件上传

nodejs--file文件上传

作者: 秋天de童话 | 来源:发表于2018-03-12 14:37 被阅读18次

文件上传

multer
cnpm i multer -D

//1、引入、配置
const multer = require('multer');
let multerObj = multer({dest:'./xxx'});

//2、加给中间件
server.use(multerObj);

//3、用file
request.files
server_multer.js

const express = require("express");
//const myBodyParser = require('./libs/my-body-parser');
//const logger = require('./libs/my-logger');
const multer = require('multer');  //文件
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser'); //文本

let server = express();
server.listen(3000);

let multerObj = multer({dest:'./upload'});
server.use(multerObj.any());
server.use(bodyParser.urlencoded({extended:false}));

//server.use(bodyParser.urlencoded({extended:false}))
//server.use(logger);
//server.use(myBodyParser.urlencoded);

server.post('/upload',(req,res,next)=>{
    console.log(req.files);

    let i=0;
    _next();
    function _next(){
        let newName = req.files[i].path + path.extname(req.files[i].originalname);

        fs.rename(req.files[i].path,newName,err=>{
            if(err){
                res.sendStatus(500,'rename error');
                res.end();
            }else{
                i++;
                if(i>=req.files.length){
                    res.send('upload ok!');
                    res.end();
                }else{
                    _next();
                }

            }
        });
    }
})

form_upload.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form1</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
    <input type='file' name='f1'></input>
    <input type="submit" value="上传"/>
    </form>
</body>
</html>

相关文章

网友评论

      本文标题:nodejs--file文件上传

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