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);
node文件上传服务器
最新推荐文章于 2024-07-11 15:17:16 发布