Skip to main content

Image Upload

WdUploadImage

Applicable Scenarios

For uploading and saving local images

Image b7df4fbe5c4f32de005143169351517b

Basic Capabilities

Bind Image and Array Field

  1. Single image upload: After the form container is bound to the data model, the "Image" field in the model will be automatically rendered as an image upload component, providing support for uploading a single image.

  2. Multiple image upload: After the form container is bound to the data model, the "Array" field of image elements in the model will be automatically rendered as an image upload component, providing support for uploading multiple images.

    Image 6db6ea39c732804c888e366dc8498441

Extended Scenarios

Obtain Image File ID After User Uploads Image

After uploading an image via the image upload component, a "File Upload" event will be triggered. The cloudID of the uploaded image can be obtained from the output parameter event.detail.value 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 shown in the figure below:

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

    Image b4a0562358859ed889241a8047738370Image 6a530af9d44d0ae066f656d7c74ccb36
  3. Preview the configuration effect: You will find that after selecting an image for upload, the cloudID of the uploaded image will be printed in the console. (Note: When the "Upload Single Image" feature of the component is disabled, multiple image uploads are supported, and the printed content will be array-type data; when this feature is enabled, only one image can be uploaded, and the printed content will be string-type data.)

    1. Print result when the Upload Single Image property is disabled.
    Image 0b44e40c9bbc28e2216d6477127353de
    1. Print result when the Upload Single Image property is enabled.
    Image 623ad25e396adfc85b9e531a52a621f5
  4. In daily usage, you can store this ID in a variable through the component's upload success event, or utilize it in other ways.

    Image 114c138e045eb39537180bd73297eb76

Practices for Other Scenarios

Refer to the Form Scenario Practice Guide to explore 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 so that only the uploader can download them, adjust the bucket access permission to "Only creator and administrator have read/write access" in the Weida environment's CloudBase-Cloud Storage module.

Image 8abdaee6-8839-402b-aab0-42d6f7a4813b

Example

Interactive Preview

Component Input Status

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

External properties received by the component

Property Name
Property Identifier
Type
Description
Bound fieldnamestring

The Key value of a form field is used to match the field identifier of the data model when submitting data. It must be unique within the form.

Title content.labelstring

Example: "图片上传"

Value storage methodstorageTypestring

Select the cloudID method, and the file will be stored directly in the data model in the form of a cloud storage fileID. Select the HTTPS method, you need to first enable public read and write permissions for cloud storage, and the file will be stored in the data model in the form of an HTTPS link.

Specify the image storage method

Default value: "cloudID"

Image valuevaluearray

Supports writing https addresses or cloudIDs to file in array format; supports string type for one upload and array type for multiple uploads.

Upload a single imagesingleboolean

To upload multiple images, you can disable this property, but you need to bind the array-image field to ensure the form is properly committed. Learn more

Enable the WeChat Mini Program to get the WeChat avatar, then only upload 1 image.

Display HeadlineslabelVisibleboolean

Default value: true

Title alignmentlabelAlignstring

In the scenario, the form by default follows the title alignment configuration of the form container.

Line break in headinglabelWrapboolean

If the title content is too long when closed, show one line with overflow omitted; when enabled, show with line breaks. In form scenarios, it follows the form container's title line break configuration by default.

Title positionlayoutstring

Set title display position in form component. In the scenario, it follows the title position configuration of the form container by default.

Title widthlabelWidthstring

You can enter a value with units such as px or %, for example: 200px.

In the scenario, the form follows the title width configuration of the form container by default.

Heading NotelabelTipsstring

Take effect on PC/H5

Configure tooltip content for the heading

Image sourcesourceTypestring

Due to browser features on all ends, when selecting "take photo," upload will be disabled on PC; when selecting "album," upload will be disabled on H5. WeChat browser on Android does not support batch selection of images.

Image selection source

Default value: "both"

WeChat Mini Program profile photo retrievalisChooseAvatarboolean

Once enabled, mini program users can select direct upload of WeChat avatar; effective only on the mini program side.

Prompt.extrastring

The prompt content is displayed below the input box after configuration.

Image shapeshowShapestring

Only affect the image display effect, without cropping the image

Default value: "ectangle"

Display underscore on mobile terminalborderedH5boolean

After closing, the mobile terminal does not show the bottom underline

Default value: true

callbacksobject

configuration-related functions

Image Compression Before UploadisCompressBeforeUploadboolean

WeChat Mini Program on iOS only supports compressing JPG formatted images

compression qualitycompressQualitynumber

This attribute is only applicable to JPG formatted images, with a range of 0–100. A smaller value indicates lower quality and a higher compression rate.

Default value: 70

Compressed image width (px)compressedWidthnumber

If empty, proportionally scale based on "compressed image height". If both properties are empty, keep the original size.

compressed image height (px)compressedHeightnumber

If empty, proportionally scale based on "compressed image width". If both properties are empty, keep the original size.

Image typeacceptTypesarray

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

Supported image type formats

Default value: ["image/*"]

Single image size cap (M)maxSizenumber

single image size cap

Default value: 10

Maximum number of imagesmaxUploadCountnumber

Maximum number of uploads allowed

Default value: 9

Status.statusstring

Example: "edit"

Requiredrequiredboolean
Required identifierrequiredFlagboolean

Enabled, the component will display a required asterisk tag if mandatory.

Default value: true

Required validation noterequiredMsgstring

Example: "该项为必填项"

Image upload templatetemplatestring

Specify an image upload template

Default value: "normal"

Pre-upload Handler Function Property

You can preprocess uploaded images using the pre-upload handler function, such as compressing, cropping, etc.

Function Parameter Types:

type BeforeUploadParams0 = {
// base64 uri
base64Uri: string[];
// Mini Program only, temporary file path array
tempFilePaths?: string[];
// web end only, File object
files: File[];
};

On the Web end, you can call external libraries like compressorjs to process File objects. For Mini Programs, you can use provided APIs such as wx.compressImage and wx.cropImage to handle temporary file paths.

Function Return Value Types:

boolean | File[] | string[]
  • Return true to continue the default upload logic.
  • Return false to disable the default upload logic.
  • The Web end returns an array of File. The Web end accepts the file[] returned by the function as the upload object to complete the upload logic.
  • The Mini Program returns a string[] array of temporary file paths. The Mini Program receives the array of temporary file paths returned by the function as the upload object to complete the upload logic.

Applications can determine the runtime environment using the Platform API to optimize multi-end custom upload logic.

Example: Custom Upload

For example, to customize the upload to other destinations such as COS Below is an example using CloudBase Cloud Storage in the WeDa environment:

async (result) => {
console.log('beforeUpload', result);
// Files 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

Events exposed by the component. You can listen to component events to trigger external actions

Event Name
Event Code
Event Output Parameters event.detail
Applicable Scenarios
Description
value changechangeobject
  • value:
  • isDelete: boolean是否删除动作
Compatible with all platforms

Trigger when a user modifies a component value

upload succeededsuccessobject
  • value:

    上传文件的fileId

  • file:

    上传文件file对象

Compatible with all platforms

-

upload failederrorCompatible with all platforms

-

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

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

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

      单张图片大小上限

      Default value: 10
    • maxUploadCount: number图片数量上限

      允许上传的最大数量

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

-

Properties API

Through the Property API, you can access the internal state and property values of components. You can access internal values using$w.componentId.propertyName, such as $w.input1.value. For details, please refer to Property API

Read-only Property Name
Property Identifier
Type
Description
Bound fieldnamestring

The Key value of a form field is used to match the field identifier of the data model when submitting data. It must be unique within the form.

Title content.labelstring
Image valuevaluearray

Supports writing https addresses or cloudIDs to file in array format; supports string type for one upload and array type for multiple uploads.

Requiredrequiredboolean
Indicates whether to displayvisibleboolean

Whether to display the component

Whether to disabledisabledboolean

Component Disabled

Specify whether it is read-only or not.readOnlyboolean

Whether the component is read-only

Image upload instanceuploadInstanceobject
Image preview listpreviewFilearray

Method API

Through the Method API, you can programmatically trigger internal methods of components, such as submitting forms, displaying popups, etc. You can call component methods using $w.componentId.methodName, such as $w.form1.submit()

Method Name
Method Identifier
Parameters
Method Description
set valuesetValueobject
  • value:
  • isDelete: boolean是否删除动作

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

Show/Hide SettingssetVisibleboolean显示

Set the component to hidden via $w.id1.setVisible(false)

Set DisabledsetDisabledboolean禁用

Set the component to disabled with $w.id1.setDisabled(true)

Clear valueclearValue

Clear the component value with $w.id1.clearValue()

Set as read-onlysetReadOnlyboolean只读

Set the component to read-only via $w.id1.setReadOnly(true)

Trigger validationhandleValidate

Validate the component value via $w.id1.handleValidate()

Clear verificationclearValidate

Clear component validation via $w.id1.clearValidate()

upload image upload images image upload upload picture upload picturesupload

Upload images via $w.id1.upload(), used when the upload template supports selecting custom images

Delete a single imagedeletestring图片cloudId

Delete a single image with $w.id1.delete(), used when support selecting custom image upload template

Update image upload configurationsetConfigobject 图片上传配置

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

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

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

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

      单张图片大小上限

      Default value: 10
    • maxUploadCount: number图片数量上限

      允许上传的最大数量

      Default value: 9

-

Style API

Through the Style API, you can override the styles of internal elements in components to achieve customization. For example, in the low-code editor, you can write styles for all button components using #wd-page-root .wd-btn, and control individual component styles with :scope. For detailed instructions, please refer toStyle API

Name
Class Name
Description and Examples
root element.wd-upload-image-rootOutermost component element
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope.wd-upload-image-root {
  /* Write CSS styles here */
}
H5 root element.wd-h5-upload-image-rootSettable root element style for the H5 side
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope.wd-h5-upload-image-root {
  /* Write CSS styles here */
}
PC-side root element.wd-pc-upload-image-rootSettable root element style for the PC side
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope.wd-pc-upload-image-root {
  /* Write CSS styles here */
}
Mini program root element.wd-mp-upload-image-rootSettable root element style for mini program
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope.wd-mp-upload-image-root {
  /* Write CSS styles here */
}
borderless status.wd-upload-image-root.is-borderlessSet component borderless status style
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope.wd-upload-image-root.is-borderless {
  /* Write CSS styles here */
}
Required status.wd-upload-image-root.is-requiredSet component required status style
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope.wd-upload-image-root.is-required {
  /* Write CSS styles here */
}
Title..wd-upload-image__labelComponent title element
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope .wd-upload-image__label {
  /* Write CSS styles here */
}
Heading disable status.wd-upload-image__label.is-disabledSet component title disable status style
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope .wd-upload-image__label.is-disabled {
  /* Write CSS styles here */
}
Create and bind a policy Query an instance Reset the access password of an instance.wd-upload-image__label.is-nowrapSet component title no-wrap status style
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope .wd-upload-image__label.is-nowrap {
  /* Write CSS styles here */
}
prompt text.wd-upload-image__helpSet the text style of the component prompt
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope .wd-upload-image__help {
  /* Write CSS styles here */
}
Verification information.wd-upload-image__errorSet component verification information style
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope .wd-upload-image__error {
  /* Write CSS styles here */
}
PC image upload click area container style.weda-uploader-btn__boxPC image upload click area container style

      :scope .weda-uploader-btn__box {
        background: #fafafa;
        border:1px dashed #d9d9d9 !important;
        border-radius: 10px;
      }
      
H5, mini program side image upload click area container style.weui-uploader__input-boxH5, mini program side image upload click area container style

      :scope .weui-uploader__input-box {
        background: #fff;
        border:1px dashed #d9d9d9;
      }
      
H5 and mini program side image upload + vertical line style.weui-uploader__input-box::before Image upload + vertical line style

      :scope .weui-uploader__input-box::before {
        background: #fff;
        content: '+';
        width: 10px;
        top:40%;
      }
      
H5 and mini program side image upload + line style.weui-uploader__input-box::after Image upload + line style

      :scope .weui-uploader__input-box::after {
        background: #fff;
        width: 50px;
        content: '上传图片';
        font-size: 12px;
      }
      
H5, mini program side image display container style.weui-uploader__fileH5, mini program side image display container style
/* :scope refers to the current component element */
/* For details, refer to the Style API documentation */
:scope .weui-uploader__file {
  /* Write CSS styles here */
}

Learn about Style API

Version Changes

  • Property Changes
  • Style Changes
  • widget api Changes

Frequently Asked Questions

What are the possible reasons for the Mini Program image upload being unresponsive?

  • When an upload fails, print error logs in the upload failure event to check the reason.
  • For Mini Program image uploads, the interface called is wx.chooseMedia. It primarily supports capturing or selecting images/videos from the phone album. When opening the Mini Program on a pc, compatibility issues with the upload interface may cause unresponsiveness. It is recommended to implement uploads via the web end instead.
  • Compatibility issues exist when using Mini Programs within WeCom. For details, refer to WeCom Mini Program API Support