参考1 http://www.cnblogs.com/yuanke...
参考2 https://github.com/felixge/no...
index.html
<body> <input name="img" type="file"> <button>submit</button> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="./test.js"></script> </body>
test.js
$("button").on("click",function (e) { e.preventDefault() var obj = new FormData(); obj.append("img",$("input").get(0).files[0]); $.ajax({ url:"http://localhost:8081/test",type:"post",data:obj,processData:false,// 不处理数据 contentType : false,// 不设置请求头 cache:false,success:function(data){ console.log(data) } }) })
node app.js
const express = require("express") const fs = require("fs") const formidable = require('formidable') const app = express() const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false })) app.post("/test",function(req,res){ // 跨域 res.header("Access-Control-Allow-Origin","*"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("Access-Control-Allow-Headers","Content-Type,Content-Length,Authorization,Accept,X-Requested-With"); let form = new formidable.IncomingForm(); form.encoding = 'utf-8'; // 编码 form.keepExtensions = true; // 保留扩展名 form.maxFieldsSize = 2 * 1024 * 1024; // 文件大小 form.uploadDir = 'C:/Users/Administrator/Downloads' // 存储路径 form.parse(req,function(err,fileds,files){ // 解析 formData数据 if(err){ return console.log(err) } let imgPath = files.img.path // 获取文件路径 let imgName = "./test." + files.img.type.split("/")[1] // 修改之后的名字 let data = fs.readFileSync(imgPath) // 同步读取文件 fs.writeFile(imgName,data,function(err){ // 存储文件 if(err){ return console.log(err) } fs.unlink(imgPath,function(){}) // 删除文件 res.json({code:1}) }) }) }) app.listen(8081)原文链接:https://www.f2er.com/ajax/161219.html