Skip to main content

Image Upload

WdUploadImage

Applicable Scenarios

to upload and store local images

Basic Capabilities

Binding "Image, Array" Fields

  1. Single image upload: After the form container is bound to the data model, the "Image" field in the model is automatically rendered as an image upload component, enabling support for single image upload.
  2. Multiple image upload: After the form container is bound to the data model, the "Array" field of image type in the model is automatically rendered as an image upload component, enabling support for multiple image uploads.

Extended Scenarios

Getting the Image File ID After User Upload

After an image is uploaded via the image upload component, the "File Upload" event is triggered. The cloudID of the uploaded image can be obtained from the event.detail.value parameter of this event. This ID can be viewed by printing logs, as shown in the following example:

  1. Create a custom method and write the log printing code console.log(event.detail.value). The specific content format is as shown in the figure below:

  2. Drag and drop the "Image Upload" component into the page, and configure the "Value Change" event to trigger this log printing method.

  3. Preview the configuration effect: you will find that when selecting images for upload, the cloudID of the uploaded images will be printed in the console (Note: When the component's "Upload Single Image" property is turned off, multiple image uploads are supported, and the printed content will be data of array type; when this property is turned on, only a single image can be uploaded, and the printed content will be data of string type).

    1. Printed result when the 'Upload Single Image' property is off

    2. Printed result when the 'Upload Single Image' property is on

  4. In daily use, you can store this ID in a variable through the component's upload success event, or utilize it in other ways.

Other Scenario Practices

Refer to the Form Scenario Practice Guide to learn about various supported scenarios and implementation solutions for forms.

Notes

caution

After an image is uploaded, users can download/view the image via its https URL. To restrict all file/image resources to be downloadable only by the uploader, set the bucket access permission to "Only creator and administrator have read-write access" in the CloudBase - Cloud Storage module of the WeDa environment.

Example

Interactive Preview

Component Input State

Style API Example

#wd-page-root .wd-form-item.wd-pc-upload-image-root .wd-upload-image__label {
color: #05c3c3;
display: flex;
justify-content: center;
align-items: center;
}

Properties

组件接收的外部传入的属性

属性名
属性标识
类型
说明
绑定字段namestring

表单字段的Key值,用于提交数据时,匹配数据模型字段标识。表单内需保证唯一。

标题内容labelstring

示例:"图片上传"

值存储方式storageTypestring

选择cloudID方式,文件将以云存储 fileID 的形式直接存储在数据模型中;选择https方式,需先开启云存储公有读写权限,文件将以https链接形式存储在数据模型中。

指定图片存储方式

默认值:"cloudID"

图片值valuearray

支持以数组格式写入文件的https地址或cloudID;上传单个时支持字符串类型,上传多个时支持数组类型

上传单个图片singleboolean

如需上传多张图片,可关闭该属性,但需绑定数组-图片字段,以保证表单的正常提交 了解详情

开启小程序端获取微信头像后,仅能上传1张图片

显示标题labelVisibleboolean

默认值:true

标题对齐labelAlignstring

表单场景下默认会跟随表单容器的标题对齐配置

标题换行labelWrapboolean

如果标题内容过长关闭时只显示一行、溢出省略;开启时换行展示。表单场景下默认会跟随表单容器的标题换行配置

标题位置layoutstring

设置标题在表单组件的展示位置,表单场景下默认会跟随表单容器的标题的位置配置

标题宽度labelWidthstring

您可以输入数值 + px、%等单位,示例:200px

表单场景下默认会跟随表单容器的标题宽度配置

标题提示labelTipsstring

PC/H5端生效

配置标题的工具提示内容

图片来源sourceTypestring

受各端浏览器特性限制,选择「拍照」时,PC端将禁用上传;选择「相册」时,H5端将禁用上传;安卓端微信浏览器不支持批量选择照片

图片选择的来源

默认值:"both"

小程序端获取微信头像isChooseAvatarboolean

开启后小程序用户可选择直接上传微信头像;仅小程序端生效

下方提示extrastring

配置后提示内容常显在输入框下方

图片形状showShapestring

只影响图片的展示效果,不会对图片进行裁剪

默认值:"ectangle"

移动端显示下划线borderedH5boolean

关闭后移动端不显示底部下划线

默认值:true

callbacksobject

配置相关的函数

上传前压缩图片isCompressBeforeUploadboolean

iOS小程序端仅支持压缩JPG格式图片

压缩质量compressQualitynumber

该属性仅对JPG格式图片有效,范围0~100,数值越小,质量越低,压缩率越高

默认值:70

压缩后图片宽度(px)compressedWidthnumber

若为空则以「压缩后图片高度」为准等比缩放;两个属性均为空时,保持图片原尺寸

压缩后图片高度(px)compressedHeightnumber

若为空则以「压缩后图片宽度」为准等比缩放;两个属性均为空时,保持图片原尺寸

图片类型acceptTypesarray

绑定表达式示例:[".jpg",".png", "image/gif"],该属性暂不支持小程序

支持上传的图片类型格式

默认值:["image/*"]

单张图片大小上限(M)maxSizenumber

单张图片大小上限

默认值:10

图片数量上限maxUploadCountnumber

允许上传的最大数量

默认值:9

状态statusstring

示例:"edit"

必填requiredboolean
必填标识requiredFlagboolean

启用后,组件若要求必填,则会显示必填星号标记

默认值:true

必填校验提示requiredMsgstring

示例:"该项为必填项"

图片上传模板templatestring

指定图片上传模板

默认值:"normal"

Pre-upload Handler Function Property

Uploaded images can be preprocessed via the pre-upload handler function, such as compression, cropping, etc.

Function Input Parameter Type:

type BeforeUploadParams0 = {
// base64 uri
base64Uri: string[];
// Exclusive to the Mini Program side, temporary file address array.
tempFilePaths?: string[];
// Exclusive to the web side, File object
files: File[];
};

On the Web side, external libraries such as compressorjs can be utilized to process File objects. For mini programs, APIs provided by the mini program like wx.compressImage and wx.cropImage can be used to process temporary file addresses.

Function return value type:

boolean | File[] | string[]
  • Returns true to continue the default upload logic.
  • Returns false to disable the default upload logic.
  • The web side returns a File array. The web side receives the file[] returned by the function as upload objects to complete the upload logic.
  • The Mini Program side returns a string[] temporary file address array. The Mini Program side receives the temporary file address array returned by the function as upload objects to complete the upload logic.

The application runtime can determine via the Platform API to refine multi-end custom upload logic.

Example: Custom Upload

For example, to customize uploading to another location such as COS. Below, using CloudBase Cloud Storage within the WeDa environment as an example:

async (result) => {
console.log('beforeUpload', result);
// Can be processed before upload, such as compression
// result.files[0] = FAKE_COMPRESS(result.files[0])

const tcb = await $w.cloud.getCloudInstance();
const res = await tcb.uploadFile({
cloudPath: 'ttt/abc.jpg',
filePath: result.files[0]
});

console.log(res.download_url); // Image HTTP address
$w.uploadImage1.setValue({ value: [res.download_url] }); // Set the obtained http address to the image upload component
return false; // Abort the upload
};

Events

组件暴露的事件,可以监听组件的事件来触发一些外部的动作

事件名
事件code
事件出参 event.detail
适用情况
说明
值改变changeobject
  • value:
  • isDelete: boolean是否删除动作
兼容三端

用户修改组件值时触发

上传成功successobject
  • value:

    上传文件的fileId

  • file:

    上传文件file对象

兼容三端

-

上传失败error兼容三端

-

上传图片初始化完成onReadyobject 图片上传实例
  • config: object 图片上传配置项
    • accepts: string允许上传的图片类型,仅支持web端
    • customUploadPath: string自定义上传路径,格式:pathA/pathB,存储在weda-uploader/appName/customUploadPath,customUploadPath默认为空
    • action: string小程序上传api

      可选值为chooseMedia,chooseMessageFile,仅小程序端生效

      默认值:chooseMedia
    • isCompressBeforeUpload: boolean上传前压缩图片
    • compressQuality: number压缩质量 默认值:70
    • compressedWidth: number压缩后图片宽度(px)
    • compressedHeight: number压缩后图片高度(px)
    • maxSize: number单张图片大小上限(M)

      单张图片大小上限

      默认值:10
    • maxUploadCount: number图片数量上限

      允许上传的最大数量

      默认值:9
  • beforeUpload: function 上传前处理函数
    参数
    • params1: object
      • files: array
        • file 对象
      • base64Uri: array
        • stringbase64
      • tmpFilePaths: array
        • string图片临时地址
    返回值
  • onUploadProgress: function 上传过程中
    参数
    • params1: object 上传图片预览信息
      • progress: number加载进度条
      • loading: boolean是否loading
      • cloudId: string云存储id
      • url: string图片https地址
      • tempUrl: string临时图片地址
      • key: stringkey
      • file: web端图片对象
    返回值
  • onComplete: function 上传事件完成
    参数
    • params1: array上传图片预览列表
      • object 上传图片预览信息
        • progress: number加载进度条
        • loading: boolean是否loading
        • cloudId: string云存储id
        • url: string图片https地址
        • tempUrl: string临时图片地址
        • key: stringkey
        • file: web端图片对象
    返回值
  • onSuccess: function 上传成功
    参数
    • params1: object 上传图片预览信息
      • progress: number加载进度条
      • loading: boolean是否loading
      • cloudId: string云存储id
      • url: string图片https地址
      • tempUrl: string临时图片地址
      • key: stringkey
      • file: web端图片对象
    返回值
  • onFail: function 上传失败
    参数
    • params1:
    返回值
兼容三端

-

Property API

通过属性 API,可以获取组件内部的状态和属性值,可以通过$w.componentId.propertyName 来访问组件内部的值,如 $w.input1.value ,详请请参考 属性 API

只读属性名
属性标识
类型
说明
绑定字段namestring

表单字段的Key值,用于提交数据时,匹配数据模型字段标识。表单内需保证唯一。

标题内容labelstring
图片值valuearray

支持以数组格式写入文件的https地址或cloudID;上传单个时支持字符串类型,上传多个时支持数组类型

必填requiredboolean
是否展示visibleboolean

组件是否展示

是否禁用disabledboolean

组件是否禁用

是否只读readOnlyboolean

组件是否只读

图片上传实例uploadInstanceobject
图片预览列表previewFilearray

Method API

通过方法 API,可以通过程序触发组件内部的方法,比如提交表单,显示弹窗等, 可以通过$w.componentId.methodName来调用组件方法,如 $w.form1.submit()

方法名
方法标识
参数
方法说明
设置值setValueobject
  • value:
  • isDelete: boolean是否删除动作

通过 $w.id1.setValue("weda") 设置组件值

设置显隐setVisibleboolean显示

通过 $w.id1.setVisible(false) 设置组件为隐藏

设置禁用setDisabledboolean禁用

通过 $w.id1.setDisabled(true) 设置组件为禁用

清空值clearValue

通过 $w.id1.clearValue() 清空组件值

设置只读setReadOnlyboolean只读

通过 $w.id1.setReadOnly(true) 设置组件为只读

触发校验handleValidate

通过 $w.id1.handleValidate() 校验组件值

清除校验clearValidate

通过 $w.id1.clearValidate() 清除组件校验

上传图片upload

通过 $w.id1.upload() 上传图片,仅在支持选择自定义图片上传模板时使用

删除单张图片deletestring图片cloudId

通过 $w.id1.delete() 删除单个图片,仅在支持选择自定义图片上传模板时使用

更新图片上传配置setConfigobject 图片上传配置

通过 $w.id1.setConfig()更新图片上传配置项,仅在支持选择自定义图片上传模板时使用

  • config: object 图片上传配置项
    • accepts: string允许上传的图片类型,仅支持web端
    • customUploadPath: string自定义上传路径,格式:pathA/pathB,存储在weda-uploader/appName/customUploadPath,customUploadPath默认为空
    • action: string小程序上传api

      可选值为chooseMedia,chooseMessageFile,仅小程序端生效

      默认值:chooseMedia
    • isCompressBeforeUpload: boolean上传前压缩图片
    • compressQuality: number压缩质量 默认值:70
    • compressedWidth: number压缩后图片宽度(px)
    • compressedHeight: number压缩后图片高度(px)
    • maxSize: number单张图片大小上限(M)

      单张图片大小上限

      默认值:10
    • maxUploadCount: number图片数量上限

      允许上传的最大数量

      默认值:9

-

Style API

通过样式 API,可以覆盖组件中内部元素的样式来实现自定义,例如在低代码编辑器中中通过 #wd-page-root .wd-btn 即可为所有的按钮组件编写样式,通过 :scope 可以控制单个组件样式, 详细说明请参考样式 API

名称
类名
说明和示例
根元素.wd-upload-image-root组件最外层元素
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope.wd-upload-image-root {
  /* 在这里编写CSS 样式 */
}
H5 端根元素.wd-h5-upload-image-root可设定 H5 端的根元素样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope.wd-h5-upload-image-root {
  /* 在这里编写CSS 样式 */
}
PC 端根元素.wd-pc-upload-image-root可设定 PC 端的根元素样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope.wd-pc-upload-image-root {
  /* 在这里编写CSS 样式 */
}
小程序端根元素.wd-mp-upload-image-root可设定小程序端的根元素样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope.wd-mp-upload-image-root {
  /* 在这里编写CSS 样式 */
}
无边框状态.wd-upload-image-root.is-borderless设置组件无边框状态样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope.wd-upload-image-root.is-borderless {
  /* 在这里编写CSS 样式 */
}
必填状态.wd-upload-image-root.is-required设置组件必填状态样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope.wd-upload-image-root.is-required {
  /* 在这里编写CSS 样式 */
}
标题.wd-upload-image__label组件标题元素
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope .wd-upload-image__label {
  /* 在这里编写CSS 样式 */
}
标题禁用状态.wd-upload-image__label.is-disabled设置组件标题禁用状态样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope .wd-upload-image__label.is-disabled {
  /* 在这里编写CSS 样式 */
}
标题不换行.wd-upload-image__label.is-nowrap设置组件标题不换行时状态样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope .wd-upload-image__label.is-nowrap {
  /* 在这里编写CSS 样式 */
}
提示文字.wd-upload-image__help设置组件提示文字样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope .wd-upload-image__help {
  /* 在这里编写CSS 样式 */
}
校验信息.wd-upload-image__error设置组件校验信息样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope .wd-upload-image__error {
  /* 在这里编写CSS 样式 */
}
PC端图片上传点击区域容器样式.weda-uploader-btn__boxPC端图片上传点击区域容器样式

      :scope .weda-uploader-btn__box {
        background: #fafafa;
        border:1px dashed #d9d9d9 !important;
        border-radius: 10px;
      }
      
H5、小程序端图片上传点击区域容器样式.weui-uploader__input-boxH5、小程序端图片上传点击区域容器样式

      :scope .weui-uploader__input-box {
        background: #fff;
        border:1px dashed #d9d9d9;
      }
      
H5、小程序端图片上传的 + 号竖线样式.weui-uploader__input-box::before 图片上传的 + 号竖线样式

      :scope .weui-uploader__input-box::before {
        background: #fff;
        content: '+';
        width: 10px;
        top:40%;
      }
      
H5、小程序端图片上传的 + 号横线样式.weui-uploader__input-box::after 图片上传的 + 号横线样式

      :scope .weui-uploader__input-box::after {
        background: #fff;
        width: 50px;
        content: '上传图片';
        font-size: 12px;
      }
      
H5、小程序端图片展示容器样式.weui-uploader__fileH5、小程序端图片展示容器样式
/* :scope 指的是当前组件元素 */
/* 具体可参考样式 API 文档 */
:scope .weui-uploader__file {
  /* 在这里编写CSS 样式 */
}

了解样式 API

Version Changes

  • Property changes
  • Style changes
  • widget api changes

Frequently Asked Questions

What are the possible reasons for unresponsive image uploads in Mini Programs?

  • When an upload fails, print error logs in the upload failure event to check the reason for the failure.
  • For image uploads in Mini Programs, the API called is wx.chooseMedia, which primarily supports capturing or selecting images/videos from the phone album. When opening the Mini Program on the pc side, there might be incompatibility issues with the upload API, leading to unresponsiveness. It is recommended to implement uploads through the web side.
  • When using Mini Programs within WeCom, compatibility issues may occur. For details, refer to WeCom Mini Program API Support