ios 将数据分割成块并上传到服务器

kq0g1dla  于 2023-07-01  发布在  iOS
关注(0)|答案(1)|浏览(143)

我有一个文件需要上传到服务器,我被告知在上传之前要将文件分成多个块。所以问题来了
1)我已经将文件转换为“数据”类型(字节)。如何将其拆分为每个1MB的块?
2)分割后,如何使用Alamofire上传?如果不可能使用Alamofire,请建议我如何做。
我用的是Swift 3和Code 8.3。任何帮助都是非常感谢的。

2g32fytz

2g32fytz1#

我想这可能有用

let path = Bundle.main.url(forResource: "test", withExtension: "png")!
    
do
{
    let data = try Data(contentsOf: path)
    let dataLen = (data as NSData).length
    let fullChunks = Int(dataLen / 1024) // 1 Kbyte
    let totalChunks = fullChunks + (dataLen % 1024 != 0 ? 1 : 0)
        
    var chunks:[Data] = [Data]()
    for chunkCounter in 0..<totalChunks
    {
        var chunk:Data
        let chunkBase = chunkCounter * 1024
        var diff = 1024
        if chunkCounter == totalChunks - 1
        {
            diff = dataLen - chunkBase
        }
            
        let range:Range<Data.Index> = chunkBase..<(chunkBase + diff)
        chunk = data.subdata(in: range)
            
        chunks.append(chunk)
    }
        
    // Send chunks as you want
    debugPrint(chunks)
}
catch
{
    // Handle error        
}

相关问题