全栈的自我修养 ———— 微信小程序实现上传并保存图片

上传文件

1、使用原生上传

uni.chooseImage({
	success: (chooseImageRes) => {
		const tempFilePaths = chooseImageRes.tempFilePaths;
		uni.uploadFile({
			url: '......',
			filePath: tempFilePaths[0],
// name是服务端的属性名
			name: 'file',
// 可添加请求头:header: { "Content-Type": "multipart/form-data" },
			success: (uploadFileRes) => {
				console.log(uploadFileRes.data);
			}
		});
	}
});

2、使用其他ui上传

这里举例u-view

          <u-upload name="filePath" accept="image" :multiple="false" :maxCount="1" @afterRead="afterRead">
            <view slot="default">
              <view class="function">
                从相册选择
              </view>
            </view>
          </u-upload>
    async afterRead(event) {
      wx.uploadFile({
        url: '......',
        header: { "Content-Type": "multipart/form-data" },
        filePath: event.file.url,
        name: event.name,
        success: async (res) => {
        // 成功后的操作
        },
        fail: function (res) {
          uni.showToast({
            icon: "error",
            title: '服务响应失败'
          });
        }
      })
    },

保存文件

    async saveAvatar() {
      uni.downloadFile({
        url: '......',
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function () {
                uni.showToast({
                  title: "保存成功"
                });
              },
              fail: function () {
                uni.showToast({
                  title: "保存失败",
                  icon: "none"
                });
              }
            });
          }
        }
      })
    },

最近更新

  1. TCP协议是安全的吗?

    2024-03-29 07:26:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-29 07:26:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-29 07:26:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-29 07:26:04       18 阅读

热门阅读

  1. python-numpy-常用函数详解

    2024-03-29 07:26:04       17 阅读
  2. 久菜盒子|毕业设计|金融|DCC-GARCH模型

    2024-03-29 07:26:04       18 阅读
  3. OpenCV图像滤波、边缘检测

    2024-03-29 07:26:04       19 阅读
  4. Redis缓存数据库表(列单独缓存)

    2024-03-29 07:26:04       16 阅读
  5. Spring Boot整合Redis

    2024-03-29 07:26:04       16 阅读
  6. 《青少年成长管理2024》 006 “成长需要教育”

    2024-03-29 07:26:04       18 阅读
  7. MyBatis3源码深度解析(二十七)MyBatis整合Spring框架

    2024-03-29 07:26:04       21 阅读