swift 阿里云文件上传

import AliyunOSSiOS

class Uploader {
    
    static let shared = Uploader()
    
    let config = OSSClientConfiguration()
    
    let credantial = OSSFederationCredentialProvider { () -> OSSFederationToken? in
        let token = OSSFederationToken()
        token.tAccessKey = AccessKey
        token.tSecretKey = SecretKey
        return token
    }
    
    let client: OSSClient
    
    init() {
        OSSLog.enable()
        
        config.maxRetryCount = 2
        config.timeoutIntervalForRequest = 30
        config.timeoutIntervalForResource = 30
        config.maxConcurrentRequestCount = 10
        
        client = OSSClient(endpoint: endPoint,
                           credentialProvider: credantial,
                           clientConfiguration: config)
    }
}

extension Uploader {
    func uploadImages(_ images: [ImageFile], completionHandler: @escaping (() -> Void)) {
        var count = images.count
        
        for image in images {
            DispatchQueue.global().async {
                self.uploadImage(image) {
                    count -= 1
                    if count == 0 {
                        completionHandler()
                    }
                }
            }
        }
    }
    
    private func uploadImage(_ image: ImageFile, completionHandler: @escaping (() -> Void)) {
        let put = OSSPutObjectRequest()
        put.contentType = "image/jpeg"
        put.bucketName = image_BucketName
        put.objectKey = image.name
        put.uploadingData = image.data ?? Data()
        put.uploadProgress = { bytesSent, totalByteSent, totalByteExpectedToSend in
            print(bytesSent, totalByteSent, totalByteExpectedToSend)
        }
        
        let putTask = client.putObject(put)
        putTask.continue({ (task: OSSTask) -> Any? in
            if task.error == nil {
                print("upload object success!")
                DispatchQueue.main.async {
                    completionHandler()
                }
            } else {
                print("upload object failed, error: \(task.error?.localizedDescription ?? "")")
            }
            return nil
        })
    }
}

struct ImageFile {
    let image: UIImage
    let name: String
    let data: Data?
    
    let maxSize: CGFloat
    
    var urlString: String {
        return image_EndPoint + "/" + name
    }
    
    init(image: UIImage, maxSize: CGFloat = 0) {
        self.image = image
        self.maxSize = maxSize
        let name = "user/" + getUUID() + ".jpg"
        self.name = name
        var quality: CGFloat = 1
        var data = image.jpegData(compressionQuality: quality)
        var sizeOriginKB: CGFloat = CGFloat((data?.count ?? 0)) / 1024.0
        if maxSize > 0 {
            while sizeOriginKB > maxSize && quality > 0 {
                quality -= 0.1
                data = image.jpegData(compressionQuality: quality)
                sizeOriginKB = CGFloat((data?.count) ?? 0) / 1024.0
            }
        }
        
        self.data = data
        print("sizeOriginKB: \(sizeOriginKB)")
        print("uuid: \(self.name)")
    }
}

func getUUID() -> String {
    let uuidRef = CFUUIDCreate(nil)
    let uuidStringRef = CFUUIDCreateString(nil,uuidRef)
    return uuidStringRef! as String
}

使用的地方

let imageFiles = viewModel.images.map { (image) -> ImageFile in
            return ImageFile(image: image)
        }
        Uploader.shared.uploadImages(imageFiles) { [weak self] in
            guard let `self` = self else { return }
            let photosUrl = imageFiles.map { $0.urlString }.joined(separator: ",")
            self.contents.result["photosUrl"] = photosUrl
            print("imageFile: \(photosUrl)")
            self.submit()
        }

你可能感兴趣的:(swift 阿里云文件上传)