nodejs express 文件上传

upload.js

var express = require('express');
var app = express();
var http = require('http');
var httpServer = http.createServer(app);
var path = require('path')
var multer = require('multer')
var upload = multer({ dest: 'tmp/' })
var fs = require('fs');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
app.all('*', function(req, res, next) {
  // console.log(req.headers.origin);
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", true); //带cookies
  res.header("X-Powered-By", ' 3.2.1')
    // res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method == 'OPTIONS') {
    res.send(200);
  } else if (req.method == 'GET') {
    req.body = req.query;
    next();
  } else {
    next();
  }
});

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
  // cookie 解析中间件
app.use(cookieParser())
app.use('/up', function(req, res) {
  // res.writeHead(200, {'Content-Type': 'text/html'});
  res.sendFile(path.join(__dirname + '/up.html'));
})
app.use('/upload', upload.single('file'), function(req, res) {
  var tmp_path = req.file.path;
  var target_path = './public/' + req.file.originalname;
  fs.rename(tmp_path, target_path, function(err) {
    if (err) throw err;
    // 删除临时文件夹文件, 
    fs.unlink(tmp_path, function() {
      if (err) throw err;
      res.send('File uploaded to: ' + target_path + ' - ' + req.file.size + ' bytes');
    });
  });
})

httpServer.listen('4000', function() {

})

up.html

<body>
  <form method="post"  action="/upload" enctype="multipart/form-data">
    <input type="text" name="name">
    <input type="file" name="file">
    <input type="submit">
  </form>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值