node图片请求及上传处理-api接口(正常例子)multer与formidable

通常前端上传图片给与后端都是通过fordata或者表单进行上传,后端服务接收到请求后将前端上传的图片保存在指定文件夹,最后再讲服务器图片地址传给前端,前端通过url或者img 的src即可进行访问

一、node服务两种方式处理上传文件(multer与formidable)
(multer)
npm i multer --save-dev(multer处理表单数据)
npm i mongodb --save-dev(操作数据库)
npm i body-parser -save-dev(post请求插件)

//引入express
let express = require('express')
//引入bodyparser 处理post请求的中间件
let bodyParser = require('body-parser')
//引入multer 处理文件上传的中间件
let multer = require('multer')
//引入fs文件模块
let fs =require('fs')
//引入mongod数据库插件
var MongoClient = require('mongodb').MongoClient;
//数据库地址
var url = "mongodb://127.0.0.1:27017";
let app = express()

//设置静态目录,上传的图片以及项目打包后的html都得放静态文件夹下才能被读取。
//静态文件夹可以设置多个,服务回根据设置顺序一一读取

//当访问/public/image时服务就会返回./public/image这个文件夹,从而可以访问其中的图片
app.use('/public/image',express.static('./public/image'))

app.use('/public',express.static('./public'))

// 跨域设置
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    console.log(req)
    next();
})

//设置post传递参数大小
app.use(bodyParser.json({ limit: '1000mb' }))
app.use(bodyParser.urlencoded({ extended: true, limit: "1000mb" }))

//设置multer服务处理
let upload = multer({
    storage:multer.diskStorage({
        //设置图片储存位置
        //file收到的文件
        destination:function(req,file,cd){
            //设置回调cd,使用该服务会将图片储存于./public/image需要与储存图片的静态目录一致,不然无法访问
            cd(null,'./public/image')
        },
        //从新设置图片名字,用时间戳加随机数,后缀名采用原图片后缀名
        filename:function(req,file,cd){
            let data=Date.parse(new Date())
            let random=Math.ceil(Math.random()*10)
            //获取后缀名,file.originalname代表原文件名加后缀名例如xx.jpg
            let arr=file.originalname.split('.')
            let lastname=arr[arr.length-1]
            //设置姓文件名
            cd(null,data+random+'.'+lastname)
        }
    })
})
//图片上传接口
app.post('/uploadimg',upload.fields([{name:'file',maxCount:1}]),(req,res)=>{
    //建立数据
    let user={
        name:req.body.name,
        //图片地址
        imageurl:(req.files.file)[0].destination+'/'+(req.files.file)[0].filename
    }
    console.log(req.files)
    console.log(user)
    //连接数据库
    MongoClient(url,(err,db)=>{
        if(err) throw err
        //连接数据库user集合里userimage列表
        let userdata=db.db('user')
        userdata.collection('userimage').insert(user,(err,result)=>{
            if(err) throw err
            err || console.log(err)
            console.log(result)
            res.json("上传成功")
        })
    })
})

app.listen(8080,()=>{console.log(8080)})

formidable(formidable不用统一fordata键值,但是他也不能重命名图片,需要通过fs模块来操作上传之后的图片来修改图片名字)

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 = './image'
    // 解析 formData数据
    form.parse(req, function (err, fileds, files) {
        if (err) throw err
        // console.log(files)
        // 获取文件路径
        let imgPath = files.img.path 
        //原来文件名
        //获取文件后缀名
        let arr = imgPath.split('.')
        let name = arr[arr.length-1]
        //新名字
        let  newname=Date.parse(new Date())+Math.ceil(Math.random()*10)+'.'+name
        //新路径
        let newurl='./image/'+newname
        //操作文件
        fs.rename(imgPath,newurl,(err)=>{
            console.log(err)
        })
    })
})

app.listen(8080, () => { console.log(8080) })

二、html(利用fordata添加图片通过ajax传递给后端)

<body>
    <input type="file" name="" id="iamge">
	<button onclick="upload()">上传</button>
</body>
<script>
    //获取上传图片节点input
    let iamge = document.getElementById('iamge')
    let iamge = document.getElementById('iamge')
	//点击事件
	upload=()=>{
		//用fordata进行添加
    	let fordata=new ForData()
    	//讲图片添加到其中
    	fordata.append('file',iamge.files[0])
    	$.ajax({
            url: "http://localhost:8081/uploadimg",
            type: "post",
            data: fordata,
            processData: false, // 不处理数据
            contentType: false, // 不设置请求头
            cache: false,
            success: function (data) {
                console.log(data)
            }
        })
	}

</script>

总的来讲milter比formidable方便得多,formidable重命名复杂许多

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值