我正在尝试从我的iOS应用上传文件到Amazon S3。我正在使用AFNetworking进行网络请求。我有以下代码将文件上传到S3:
func uploadFile(filePath: String, uploadUrl: String, returnDict: NSDictionary? = nil) {
let fileName = filePath.lastPathComponent
let fileType = fileName.pathExtension
if fileName != "" && fileType != "" {
if let data = NSData(contentsOfFile: filePath) {
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("\(data.length)", forHTTPHeaderField: "Content-Length")
let request = manager.requestSerializer.multipartFormRequestWithMethod("PUT",
URLString: uploadUrl,
parameters: ["Content-Type":"\(fileType)"],
constructingBodyWithBlock: { (formData :AFMultipartFormData!) -> Void in
formData.appendPartWithFileData(data,
name: "file",
fileName: uploadUrl.lastPathComponent,
mimeType: FileUploader.mimeType[fileType])
},
error: nil)
let operation = manager.HTTPRequestOperationWithRequest(request,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
println(uploadUrl)
self.delegate?.fileUploadComplete?(true, returnDict: returnDict)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println("Error : " + error.description)
self.delegate?.fileUploadComplete?(false, returnDict: nil)
})
operation.setUploadProgressBlock({ (bytesWritten: UInt,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) -> Void in
println("Wrote \(totalBytesWritten)/\(totalBytesExpectedToWrite)")
})
manager.operationQueue.addOperation(operation)
}
else {
println("File data nil")
delegate?.fileUploadComplete?(false, returnDict: nil)
}
}
else {
println("File path not correct")
delegate?.fileUploadComplete?(false, returnDict: nil)
}
}
文件完全上传到S3,但格式错误(/已损坏)。如果我上传音频,当我使用相同的网址重新下载时,文件无法播放。代表。方法仅用于通知侦听器成功或失败。由于文件大小对我来说可能太大,我需要进行分段上传。