1、抉择图片到node服务器
uni-app代码
uni.chooseImage({ success: (res) => { let tempFilePaths = res.tempFilePaths; tempFilePaths.forEach((item) => { uni.uploadFile({ url: '', //服务器地址 fileType: "image", //ZFB必填,不然报错 filePath: item, //这个就是咱们下面拍照返回或者先中照片返回的数组 name: 'file', success: (uploadFileRes) => { } }); }) }});
node服务代码
const path = require("path"); //导入path模块const multer = require("multer"); //导入multer模块const fs = require("fs"); //导入文件操作模块const util = require("../public/util");const upload = multer({ dest: "tmp/" });let express = require("express");let router = express.Router();router.post("/upload", upload.single("file"), function (req, res) { let imgFile = req.file; //获取图片上传的资源 var tmp = imgFile.path; //获取长期资源 let ext = path.extname(imgFile.originalname); //利用path模块获取 用户上传图片的 后缀名 let newName =util.getNowFormatDate('-','-')+ "-"+new Date().getTime() + Math.round(Math.random() * 10000) + ext; //给用户上传的图片重新命名 避免重名 let newPath = "/public/images/" + newName; //给图片设置寄存目录 提前给以后文件夹下建设一个 images文件夹 !!!! let fileData = fs.readFileSync(tmp); //将上传到服务器上的长期资源 读取到 一个变量外面 let filePath = path.join(__dirname, '..'+newPath); fs.writeFileSync(filePath, fileData); //从新书写图片文件 写入到指定的文件夹下 res.send(newPath); //上传胜利之后 给客户端响应});router.get('/public/images/*', function (req, res) { let newPath = ".."+req.url; let filePath = path.join(__dirname,newPath); res.sendFile(filePath);})module.exports = router;
2、抉择图片到云贮存
uni.chooseImage({ success: (res) => { let tempFilePaths = res.tempFilePaths; tempFilePaths.forEach((item) => { uniCloud.uploadFile({ filePath: item, cloudPath: 'item.jpg', success(res) { }, fail(res) { }, complete() {} }); }) }});