# UniCloud 云开发

  • 创建项目
  • 链接云环境
  • 编写代码
    • 云函数
    • 上传文件

# 编写云函数

代码示例

exports.main = async (event, context) => {
  //  event 用户提交的参数

  console.log("event: " + event);

  // 返回响应
  return event;
};

# 连 collection

const collection = db.collection("user");

# 增 add

const res = collection.add(
	{
		name:"gausszhou",
		type:"person"
	},
	...
	)

# 查 where get

const res = collection.doc("sdf80asdf7968s9d6fs86f");
// 遍历查找
const res = collection.where({ name: "gausszhou" }).get();

# 改 set update

// set 没有就新增
const res = collection.doc("sdfsfsdfosf").set({
  name: "evanyou",
  type: "大神"
});

// update 更新指定文档记录 该记录必须存在,且字段存在
const res = collection.doc("sdfsfsdfsfdsf").update({
  name: "evanyou",
  type: "大神"
});

# 删 remove

const res = collection.doc("sdf80asdf7968s9d6fs86f").remove();

# 调用云函数

uniCloud.callFunction();

# 上传文件

uniCloud.uploadFile

chooseImage() {
	let that = this;
	uni.chooseImage({
		count: 1,
		success(res) {
			console.log(JSON.stringify(res, null, 2));
			const tempPath = res.tempFilePaths[0];
			that.uploadFile(tempPath);
		},
		fail(err) {}
	});
},
uploadFile(path) {
	let that = this;
	uniCloud.uploadFile({
		filePath: path,
		// 文件名
		cloudPath: Date.now(),
		success(res) {
			console.log(JSON.stringify(res, null, 2));
			that.imgList.push(res.fileID);
			// fileID 就是云空间文件路径
		},
		fail(err) {
			console.log(err);
		}
	});
},

deleteImage(img) {
	let that = this;
	uniCloud.deleteFile({
		// 阿里云只支持一次删除一个文件
		fileList: [img],
		success(res) {
			console.log(JSON.stringify(res, null, 2));
			// 删除成功,在数组中去除
			const index = that.imgList.findIndex(item=>item == img)
				that.imgList.splice(index,1)
		},
		fail(err) {
			console.log(err);
		}
	});
}

errMsg

{
  "errMsg": "chooseImage:ok",
  "tempFilePaths": ["blob:http://192.168.1.103:8080/e63a955a-4dc8-4f3c-a745-296265b54dd0"],
  "tempFiles": [{}]
}

success

{
  fileID: "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-82565262-b2d0-4153-800c-92e9f4287cc2/94c256a7-eebd-46cb-b3b2-2691a0132d3a.";
  filePath: "blob:http://localhost:8080/7907c6a1-0ee3-42c8-b38d-fd436992e0ab";
  success: true;
}