react+antd的Upload上传文件至oss(上传文档转图片)

又来码字了,公司需求要上传文件到阿里的oss上,之前没有做过,这次踩了两天的坑才爬出来,我太难了…还好最后完成,特此记录帮助以后的有需要的小伙伴们少走弯路…
还有就是阿里的demo真的是写的太lan了…把我看得云里雾里…最后还是参考网上的写法完成了需求…

主要代码
import { Upload} from 'antd';
<Upload 
    name="file" 
    action=""
    onChange={this.uploadFile}
    headers={config.headerAuth}
    showUploadList={false}
    data={uploadParmas}
    accept=".pdf,.doc,.docx,.ppt,.pptx"
    beforeUpload={this.beforeUpload}
    >
    {!this.state.progressShow && <span>+上传文档</span>} //上传完成后隐藏
</Upload>

//采用手动上传的方式
beforeUpload = (file) => {
    let files = [];
    this.setState({
        fileList: [...files]
    })
     return false;
}

//主要核心代码
uploadFile = (info) => {
        let { liveInfo } = this.props;
        const isPDF = info.file.type === 'application/pdf';
        const isDOC = info.file.type === 'application/msword';
        const isDOCX = info.file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        const isPPT = info.file.type === 'application/vnd.ms-powerpoint';
        const isPPTX = info.file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        const isLt8M = info.file.size / 1024 / 1024  < 100;
        if (!isPDF && !isDOC && !isDOCX && !isPPT && !isPPTX) {
            message.error('你只能上传pdf|doc|docx|ppt/pptx文件!');
            return false;
        }else{
            if (!isLt8M) {
                message.error('文件必须小于8MB!');
                return false;
            }
        }
        let param_first = {
            uid:getUid(),
            room_id:liveInfo.id,
            raw_name:info.file.name
        };
        request(`http://xxxxxxx`, {  //用于获取上传oss所需要的数据
                method: 'POST',
                headers: config.headers,
                body:config.parseJson(param_first)
        }).then((res) => {
            ossConfig = {
                policy:res.data.policy,
                OSSAccessKeyId:res.data.accessid,
                callback:res.data.callback,
                signature:res.data.signature,
                url:res.data.host,
                dir:res.data.dir,
            };
            const photo = info.fileList[0].originFileObj;  // 获取图片对象
            const photoName = moment().format('YYYYMMDDHHmmss') + (Math.floor(Math.random() * 3665668)) + '.' + photo.name.split(".")[1];  // 原图片的名称
            const key = ossConfig.dir + getUid() + '/' + liveInfo.id + '/' + photoName;  // 存储到oss的图片名称 自己定,必须确保唯一性,不然会覆盖oss中原有的文件   拼接:dir/账号/房间号/文件名(记住一定要加上dir拼接!!!!!!!!!)---不要问为什么 不加你会很惨
            const policy = ossConfig.policy; // 服务器端同事调oss的API,通过接口返回给前端的 policy
            const OSSAccessKeyId = ossConfig.OSSAccessKeyId;  // 服务器端同事调oss的API,通过接口返回给前端的 OSSAccessKeyId
            const callback = ossConfig.callback;  // 服务器端同事调oss的API,通过接口返回给前端的 callback。这个是需要 oss 触发这个回调来通知服务器操作结果。
            const signature = ossConfig.signature;  // 服务器端同事调oss的API,通过接口返回给前端的 signature。这个就是签名,最关键的。
            const url = ossConfig.url;
            const dir = ossConfig.dir;
            // biu一下,提交给oss
            let param = {
                name:photoName,
                key,
                policy:policy,
                OSSAccessKeyId:OSSAccessKeyId,
                success_action_status:'200',  //必须这么写 不要问为什么
                callback:callback,
                signature:signature,
                file:photo   //一定在最后面
            };  //顺序最好按照我写的  不要动位置 要不然不保证你能活着走下去..哈哈
            const formData = new FormData();  //以表单的形式传递给oss
            Object.keys(param).forEach((key) => {
              formData.append(key, param[key]);
            });
            //请求oss上传
            request(url, {
                method: 'POST',
                headers: {
                },
                body: formData,
            }).then((res) => {
                let obj = {
                    "filepath":key,
                    "uid":getUid(),
                    "room_id":liveInfo.id,
                    "file_url":res.data.data.file_url,
                    "action":'transfer'
                };
                request('http://xxxxxx',{  //上传完成后  后端做处理(此处是因为业务需求是把文档转为图片 所以需要处理)--此步骤可省略
                    method:'POST',
                    headers:{
                        "Content-Type": "application/json"
                    },
                    body:JSON.stringify(obj)
                }).then(res=>{
                    console.log(res)
                })
            })
        });
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值