node文件上传服务器

const http = require('http');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
var header={};
header["Content-Type"]="text/plain";
//设置cors
header["Access-Control-Allow-Origin"]="http://localhost";
header["Access-Control-Allow-Headers"]="X-Requested-With";
header["Access-Control-Allow-Methods"]="PUT,POST,GET,DELETE,OPTIONS";
// header["Access-Control-Allow-Credentials"]='true';
var header1={};

//设置cors
header1["Access-Control-Allow-Origin"]="http://localhost";
header1["Access-Control-Allow-Headers"]="X-Requested-With";
header1["Access-Control-Allow-Methods"]="PUT,POST,GET,DELETE,OPTIONS";

const server = http.createServer((req, res) => {
    // 发送post会发起一次预检请求
    if (req.url == '/dopost' && req.method.toLowerCase() == 'options'){

          res.writeHead(204, header1);
          res.end();

    }
    if (req.url == '/dopost' && req.method.toLowerCase() == 'post'){
        var form = new formidable.IncomingForm();
        // 设置文件保存路径,相对路径
        form.uploadDir = "./uploads";
        // 解析表单, fields表示文本域,files表示文件域
        form.parse(req, function(err, fields, files) {
            //获得上传文件的后缀名
            //path.extname获得的是文件从'.'开始到最后的扩展名(是最后一个.)
            var extname=files.file.name;
            //获得上传文件时的路径
            const oldPath=__dirname+"/"+files.file.path;
            //获得放到目的目录的路径
            const newPath=__dirname+"/uploads/"+extname;
            //在上传文件成功之后,用rename参数进行修改文件名
            //rename的参数有两种使用方法,就是下方的样子,参数为(oldPath,newPath,callback),另一中方法是(oldPath,newPath),即少了回掉函数
            fs.rename(oldPath,newPath,(err)=>{
                if(err){
                    throw Error('改名失败');
                }
                res.writeHead(200, header);
                res.end();
            })
            
        });

    }
});
server.listen(3000); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值