关于钉钉H5微应用附件的上传和预览

1,855 阅读2分钟

背景:

相信很多小伙伴,在做每个web项目的时候,基本都会涉及到附件、图片的上传、下载预览等系列问题,如果使用第三方的ui库,还会二次封装一个Uploader组件方便使用。而如果在小程序中,这种情况可能不被允许,比如钉钉,钉钉内部只支持图片的预览,而word、excel、pdf等附件钉钉是没有提供直接预览的API的,而是需要将附件传入钉盘中,再调用钉盘的预览api才可以实现附件的预览功能。

相关API

  1. uploadAttachmentToDingTalk 此接口支持照片、拍照、本地系统文件和从已有钉盘文件选择,上传到参数为spaceId指定的钉盘空间再返回。 每个钉盘默认都会有一个空间,服务端调用获取空间列表API即可看到
  2. previewFileInDingTalk 调用dd.previewFileInDingTalk预览钉盘文件

注意:以上两个API都需要安装的dingtalk-jsapi版本在3.0.27及以上

第一步:获取空间列表

这个步骤需要使用钉钉服务端SDK,我这里用官网提供的JAVA版本的代码模拟一下:

package com.example.springbootproject02;

import com.aliyun.tea.*;
import com.aliyun.teautil.*;
import com.aliyun.teautil.models.*;
import com.aliyun.dingtalkdrive_1_0.*;
import com.aliyun.dingtalkdrive_1_0.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;

public class GetSpace {

    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkdrive_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkdrive_1_0.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkdrive_1_0.Client client = GetSpace.createClient();
        ListSpacesHeaders listSpacesHeaders = new ListSpacesHeaders();
        listSpacesHeaders.xAcsDingtalkAccessToken = "<your access token>";//token
        ListSpacesRequest listSpacesRequest = new ListSpacesRequest()
                .setUnionId("")//用户unionId 需要查询用户详情接口获取
                .setSpaceType("org")//空间类型
                //.setNextToken("2CMlB97VtVJWfoVliPIXPUQiEiE")
                .setMaxResults(50);//分页大小
        try {
            ListSpacesResponse listSpacesResponse = client.listSpacesWithOptions(listSpacesRequest, listSpacesHeaders, new RuntimeOptions());
            System.out.println(listSpacesResponse);
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性,可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性,可帮助开发定位问题
            }

        }
    }
}

我们用之前获取到的token等相关参数模拟一下,然后执行打印数据看一下结果:

image.png 这样就能获取到我们需要的spaceId了

第二步:上传附件
<script setup lang="ts">
import * as dd from 'dingtalk-jsapi'
//调用文件
const callUplad = () => {
  dd.uploadAttachmentToDingTalk({
    file: { max: 9, spaceId: '12345' },
    image: {
      max: 9,
      spaceId: '12345',
      compress: true,
      multiple: true,
    },
    space: {
      max: 9,
      corpId: 'ding1234xxx',
      spaceId: '12345',
      folderId: '123',
    },
    types: ['photo', 'camera', 'file', 'space'],
    success: (res:any) => {
      const { data, type } = res;
      console.log("data:",data)
      console.log("type:",type)
    },
    fail: (err:any) => { 
      console.log("err:",err)
    },
    complete: () => { 
      console.log("complete")
    },
  });
}
</script>

<template>
  <div>
    <button @click="callUplad">调用文件</button>
  </div>
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

我们将上面的代码中的spaceId、corpId都换成我们刚刚获取到的和企业后台的对应ID,然后执行:

406c5cc92c936aa258cfd3079139a09.jpg

a04bfd7845219f957e44b26c21c74ba.jpg

然后我们选择一个文件后,查看后台输出结果:

image.png 这样我们上传附件到钉盘就成功了!

第三部:附件预览

我们在源代码再加一个附件预览的按钮,然后绑定一个方法:

//预览附件
const perviewFile = () => {
  dd.previewFileInDingTalk({
    corpId: 'ding**',
    fileId: '333222',
    spaceId: '43333',
    fileName: '集体照.png',
    fileSize: '1024',
    fileType: 'png',
    success: () => { },
    fail: () => { },
    complete: () => { },
  });
}

将上面的corpID、fileId等参数值替换成为第二步获取到的值即可:

ae2d20691cc2f56d0ef37c4f2c6148f.jpg

以上就是在钉钉云盘内的关于附件上传和预览总结,在这个过程中,有些API是需要授权才会被允许使用的,这个需要我们到后台对应应用》权限管理中配置一下!