加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:28:03 所属栏目:百科 来源:网络整理
导读:图片上传,解析formData数据,存储文件。 参考1 http://www.cnblogs.com/yuanke... 参考2 https://github.com/felixge/no... index.html body input name="img" type="file" buttonsubmit/button script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.m

图片上传,解析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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读