美文网首页
golang oss表单上传

golang oss表单上传

作者: EasyNetCN | 来源:发表于2020-07-27 13:07 被阅读0次

    在涉及基于阿里云oss服务的时候,绝大多数情况都是基于表单上传,服务器端生成所需要的信息,这样可以不走本身服务器的流量,灵活并且方便控制。原来基于Java实现的,oss的Java客户端提供了很方便的方法生成policy和signature,golang的客户端貌似没有便捷的方法。以下实现的代码片段仅供参考。

    func (s *ossFileService) GetUploadToken(uploadFile model.OssUploadFile) *model.OssUploadToken {
        ossBucket := s.ossBucketRepository.FindById(uploadFile.FileType)
    
        if ossBucket.Id > 0 {
            fileKey := generateFileKey(uploadFile)
    
            fileEntity := new(repository.OssFile)
    
            fileEntity.BucketId = ossBucket.Id
            fileEntity.FileKey = fileKey
            fileEntity.SourceFile = uploadFile.SourceFile
            fileEntity.SourceFileSize = uploadFile.SourceFileSize
            fileEntity.DelStatus = 0
    
            now := time.Now()
    
            fileEntity.CreateTime = now
            fileEntity.UpdateTime = now
    
            result := s.ossFileRepository.Create(*fileEntity)
    
            bucketType := ossBucket.BucketType
            bucket := ossBucket.Name
            endpoint := ossBucket.Endpoint
            domain := ossBucket.Domain
            accessKeyId := s.ossClient.Config.GetCredentials().GetAccessKeyID()
            secretAccessKey := s.ossClient.Config.CredentialsProvider.GetCredentials().GetAccessKeySecret()
            uploadUrl := fmt.Sprintf("//%s.%s", bucket, endpoint)
    
            expiration := time.Now().Add(time.Duration(30 * time.Minute)).UTC().Format(time.RFC3339Nano)
            policyStr := fmt.Sprintf(`{"expiration":"%s","conditions":[{"bucket":"%s"},["eq","$key","%s"]]}`, expiration, bucket, fileKey)
    
            fmt.Println(policyStr)
    
            policy := base64.StdEncoding.EncodeToString([]byte(policyStr))
    
            key := []byte(secretAccessKey)
            mac := hmac.New(sha1.New, key)
            mac.Write([]byte(policy))
    
            signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
    
            return &model.OssUploadToken{
                FileId:      result.Id,
                UploadUrl:   uploadUrl,
                AccessKeyId: accessKeyId,
                Policy:      policy,
                Signature:   signature,
                Key:         fileKey,
                Url:         getUrl(bucketType, bucket, endpoint, fileKey, domain)}
    
        }
    
        return nil
    }
    

    相关文章

      网友评论

          本文标题:golang oss表单上传

          本文链接:https://www.haomeiwen.com/subject/lxrzlktx.html