nodejs--file文件上传

文件上传

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




    
    
    form1
    



    

你可能感兴趣的:(nodejs--file文件上传)