node处理上传图片,解析,存储路径

图片上传,解析formData数据,存储文件。

参考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)

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...