Browse SDKs · WASM
SDKsWASM

Upload a file

Upload a file independently and obtain its resource URL with the WASM SDK.

Copy

uploadFile() is an independent upload capability for user avatars, group avatars, profile attachments, and other application files. It does not belong to the message domain and does not create a message automatically.

Parameters

ParameterTypeRequiredDescription
namestringYesFilename.
contentTypestringYesMIME type.
uuidstringYesStable local identifier for this upload.
fileFileConditionalFile object in a browser environment. Provide either file or filepath.
filepathstringConditionalFile path in a runtime that supports paths. Provide either filepath or file.
causestringNoApplication-defined reason for the upload.
const { data } = await openimsdk.uploadFile({
  name: file.name,
  contentType: file.type || 'application/octet-stream',
  uuid: crypto.randomUUID(),
  file,
  cause: 'user-avatar',
});

await saveAvatarURL(data.url);

When the Promise resolves, use data.url as the remote resource URL. It means only that the upload request succeeded; it does not mean the avatar profile has been updated or a chat message has been created or sent. Complete the subsequent business write separately. If the resource will be used in chat, create the corresponding message object from the returned URL and then send it explicitly.

Listen for upload progress

CbEvents.OnProgress reports upload progress, while CbEvents.UploadComplete provides completion information. Keep stable handler references and call off() with those same references when the account or state layer is destroyed:

function handleUploadProgress({ data }) {
  updateUploadProgress(data.clientMsgID, data.progress);
}

function handleUploadComplete({ data }) {
  completeUpload(data.uuid, data.fileSize, data.streamSize);
}

openimsdk.on(CbEvents.OnProgress, handleUploadProgress);
openimsdk.on(CbEvents.UploadComplete, handleUploadComplete);

function removeUploadListeners() {
  openimsdk.off(CbEvents.OnProgress, handleUploadProgress);
  openimsdk.off(CbEvents.UploadComplete, handleUploadComplete);
}

Associate an independent upload task with a stable ID generated by your application. Do not match concurrent uploads by filename or array position.