如何通过JavaScript下载D365的Notes附件,求可用代码示例
D365 Notes附件下载JavaScript实现方案
以下代码可直接在D365模型驱动应用的客户端脚本、表单按钮事件中复用,基于官方Web API实现,无额外依赖。
完整可复用代码
/** * 下载D365指定记录关联的Notes附件 * @param {string} parentEntityLogicalName 关联父记录的实体逻辑名称,比如account、contact * @param {string} parentRecordId 关联父记录的GUID * @param {string} [annotationId] 可选,指定要下载的单条注释ID,不传则下载该记录所有附件 */ async function downloadD365NoteAttachments(parentEntityLogicalName, parentRecordId, annotationId) { // 1. 构造查询条件 let filter = `_objectid_value eq ${parentRecordId.replace(/[{}]/g, '')} and isdocument eq true`; if (annotationId) { filter += ` and annotationid eq ${annotationId.replace(/[{}]/g, '')}`; } const queryUrl = `${Xrm.Utility.getGlobalContext().getClientUrl()}/api/data/v9.2/annotations?$select=filename,documentbody,mimetype&$filter=${filter}`; try { // 2. 调用Web API获取附件数据 const response = await fetch(queryUrl, { headers: { 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Accept': 'application/json', 'Prefer': 'odata.include-annotations="*"' }, credentials: 'include' }); if (!response.ok) throw new Error('附件数据查询失败'); const result = await response.json(); const attachments = result.value; if (attachments.length === 0) { alert('当前记录无可用附件'); return; } // 3. 逐个下载附件 for (const attach of attachments) { // 转换base64为blob const byteCharacters = atob(attach.documentbody); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += 512) { const slice = byteCharacters.slice(offset, offset + 512); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, { type: attach.mimetype }); // 触发浏览器下载 const downloadUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = downloadUrl; a.download = attach.filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(downloadUrl); } } catch (e) { console.error('附件下载失败:', e); alert(`下载失败:${e.message}`); } }
调用示例
如果是在表单的自定义按钮点击事件中调用,直接获取当前表单上下文即可:
// 表单按钮触发逻辑示例 function onDownloadAttachmentButtonClick(formContext) { const parentEntityName = formContext.data.entity.getEntityName(); const parentRecordId = formContext.data.entity.getId(); // 调用下载方法,此处示例下载当前记录所有附件 downloadD365NoteAttachments(parentEntityName, parentRecordId); }
注意事项
- 代码适配D365 v9.x及以上版本,低版本环境可将Web API版本号
v9.2替换为对应环境的版本 - 需确保当前登录用户对
注释(annotation)实体有读权限,同时对关联的父记录有访问权限 - 单附件大小超过10MB时建议单独触发下载,避免批量下载导致浏览器卡顿
- 部分特殊格式文件名如果出现乱码,可对
a.download的文件名值做URI编码处理
内容的提问来源于stack exchange,提问作者Kim Meyer Albrechtsen
相关产品推荐
相关产品推荐

