node.js服务端处理文件上传的完整流程

在本文 微信小程序-从相册获取图片 使用相机拍照 本地图片上传之前需要看看

微信小程序-获取用户session_key,openid,unionid - 后端为nodejs

代码封装是在上文添加的。

本文知识点:

1、微信小程序选择图片wx.chooseImage()接口的使用

2、微信小程序选择视频wx.chooseVideo()接口的使用

3、微信小程序上传文件接口wx.uploadFile()的使用

4、nodejs上传文件multer模块的使用

效果

注意:
1、在微信开发工具里选择视频接口wx.chooseVideo()返回的数据有视频缩略图字段(thumbTempFilePath),在真机上没有;
2、上传视频时,compressed压缩字段无效,不知是所有手机无效还是部分,本文测试时,使用的是华为mate9,这也是小程序的深坑之一;
3、上传视频时,使用录制方式,华为mate9视频大小过大,录制的6秒钟视频就有20多M,网上说好像mate9的视频编码格式是h265,普通手机为h264,也许是无法压缩问题引起的;

所以尝试了另外一种方式录制,使用camera组件,这种方式需要自己自定义录制界面:点击这里。

微信小程序代码:

openAlbum : function(){
        let self = this;
        wx.chooseImage({
            success: function(res) {
                let tempFiles = res.tempFiles;
                self.setData({
                    imgList : tempFiles[0].path
                })
                console.log("tempFiles is ",tempFiles);
                wx.uploadFile({
                    url: 'http://localhost:8000/uploadImage',
                    filePath: tempFiles[0].path,
                    header : {
                        'content-type':'multipart/form-data'
                    },
                    name: 'file',
                });
            },
        })
    },


nodejs 服务端代码

const multer = require('multer');  
let path = require("path");  
//上传文件配置  
const storage = multer.diskStorage({  
  //文件存储位置  
  destination: (req, file, cb) => {  
    cb(null, path.resolve(__dirname, '../uploads/tmp/'));  
  },  
  //文件名  
  filename: (req, file, cb) => {  
    cb(null, `${Date.now()}_${Math.ceil(Math.random() * 1000)}_multer.${file.originalname.split('.').pop()}`);  
  }  
});  
const uploadCfg = {  
  storage: storage,  
  limits: {  
    //上传文件的大小限制,单位bytes  
    fileSize: 1024 * 1024 * 20  
  }  
};  
router.post("/api/upload", async (req, res) => {  
  let upload = multer(uploadCfg).any();  
  upload(req, res, async (err) => {  
    if (err) {  
      res.json({ path: `//uploads/tmp/${uploadFile.filename}` });  
      console.log(err);  
      return;  
    };  
    console.log(req.files);  
    let uploadFile = req.files[0];  
    res.json({ path: `//uploads/tmp/${uploadFile.filename}` });  
  });  
}) 


原文:https://blog.csdn.net/zzwwjjdj1/article/details/79376400 
 

猜你喜欢

转载自blog.csdn.net/lck8989/article/details/83958482