以数据块拆分数据并上传到服务器

时间:2017-09-28 08:14:13

标签: ios alamofire swift-data

我有一个需要上传到服务器的文件,我被告知在上传之前将文件分成多个块。所以这是一个问题:

1)我已将文件转换为“数据”类型(字节)。如何将其分成每个1MB的块? 2)拆分后,如何使用Alamofire上传?如果不能使用Alamofire,请推荐我该怎么做。

我正在使用swift 3和Code 8.3。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

我认为这可能有用

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> = Range<Data.Index>(chunkBase..<(chunkBase + diff))
        chunk = data.subdata(in: range)

        chunks.append(chunk)
    }

    // Send chunks as you want
    debugPrint(chunks)
}
catch
{
    // Handle error        
}