I have a file that needed to be uploaded to a server and I have been told to separate the file into multiple chunks before uploading. So here is the question:
我有一个文件需要上传到服务器,我被告知在上传之前将文件分成多个块。所以这是一个问题:
1) I have converted the file into "Data" type (bytes). How do I split it into chunks of 1MB each?
2) After splitting, how do I upload it using Alamofire? if not possible using Alamofire, pls recommend how do I do it.
1)我已将文件转换为“数据”类型(字节)。如何将其拆分为每个1MB的块? 2)拆分后,如何使用Alamofire上传?如果不能使用Alamofire,请推荐我该怎么做。
I'm using swift 3 and Code 8.3. Any help is much appreciated.
我正在使用swift 3和Code 8.3。任何帮助深表感谢。
1 个解决方案
#1
2
I think this may work
我认为这可行
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
}
#1
2
I think this may work
我认为这可行
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
}