【node】---multer模块实现图片上传---【凡尘】

1、安装muterl第三方模块

cnpm install multer --save

2、使用

multer在解析完成后,会向request对象中添加一个body对象和一个file或者files对象(上传多个文件的时候用files对象),其中body中包含提交的字段,而file中包含上传的文件

//1、引入express模块
const express = require("express");

//2、引入multer模块
const multer = require("multer");

//3、对上传的文件进行配置
var storage = multer.diskStorage({

//指定文件上传到服务器的路径
  destination: function (req, file, cb) {
    cb(null, '/public/img')
  },

//指定上传到服务器文件的名称
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
 
var upload = multer({ storage: storage })


//4、使用 在使用路由的时候调用upload方法 name值是客户端传递的key值
var cpUpload = upload.fields([{ name: 'goodsImg', maxCount: 1 }, { name: 'goodsImgs', maxCount: 8 }])
router.post('/goods/addGoods',cpUpload,goodsController.addgoods );

 

3、upload方法

upload.single('key值'):当传递单个文件的时候,对文件的解析

upload.array('key值', maxCout):当传递一组文件的时候,对文件的解析 key值是前端传递的key值 maxcout是最多能传递多少个文件

upload.fields([{ name: 'key值', maxCount: num }, { name: 'key值', maxCount: num }]):当传递多个文件域的时候,对文件的解析

4、客户端传递图片

//创建一个表单数据对象
var formData = new FormData();
var goods_name = $("#goods_name");
var goods_des = $("#goods_des");
var goods_price = $("#goods_price");
var goods_img = $("#goods_img");
var goods_imgs = $("#goods_imgs");
formData.append("goodsName",goods_name.val());
formData.append("gooddsDes",goods_des.val())
formData.append("goodsPrice",goods_price.val())
formData.append("goodsImg",goods_img[0].files[0])
for(var i=0;i<goods_imgs[0].files.length;i++){
formData.append("goodsImgs",goods_imgs[0].files[i])
}

$.ajax({
type:"post",
url:"/api/goods/addGoods",
cache: false,//不适用缓存中的结果
processData: false,//传输的数据,不被jquery封装
contentType: false,//数据编码格式不使用jquery的方式
data:formData,
success:$.proxy(this.handleSuccCb)
})
 

猜你喜欢

转载自www.cnblogs.com/nanianqiming/p/9104067.html