0

我正在使用一个使用多部分表单数据接受视频上传的 API。我想使用 NSURLSession.uploadTask (加上它的代表)来处理上传。

我的问题是我需要更改本地视频文件以使用我正在使用的 API,我创建了一个我想做的示例:

let localVideoURL = URL(string: "file://AGoodURL/video.mov")!
let apiURL = URL(string: "https://myServer.com/upload")

func uploadVideo() {

let config = URLSessionConfiguration.background(withIdentifier: "myUploads")
let session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)

var request = NSMutableURLRequest(url: apiURL!)
request.httpMethod = "POST"

// create a new file from the local file + required api data

var boundary : String {

    return "Boundary-\(UUID().uuidString)"
}

// what should be a new file and not an in memory data object, but how?
var data = Data()

// do I need to set these or will the uploadTaskWithFile class handle it?
data.append("--\(boundary)\r\n".data(using: .utf8)!)

data.append("Content-Disposition: form-data; name=\"video\"; filename=\"video.mov\"\r\n".data(using: .utf8)!)

// same question? does this need to be here?
data.append("Content-Type: video/quicktime\r\n\r\n".data(using: .utf8)!)

/** somehow get the data from the local url without loading it into memory */
// data.append(try! Data(contentsOf: localVideoURL)) /** not like this! */

data.append("\r\n".data(using: .utf8)!)
data.append("--\(boundary)--\r\n".data(using: .utf8)!)

// close the new file
// begin an uploadTask with the new file, use URLSessionDelegates.

session.uploadTask(with: request, fromFile: )

}

我将如何创建一个新的本地文件,如上所述添加字符串数据,附加本地视频文件并添加其余的字符串数据?这些文件可能非常大,因此将它们全部保存在磁盘上很重要。

4

1 回答 1

0

解决方案是将输入和输出流与新的本地临时文件一起使用,在创建输出流后,我附加多部分表单上传所需的标头数据,然后以块的形式附加现有的本地文件,然后附加关闭数据(如边界)并关闭流。

然后我使用该文件,该文件使用带有文件的 NSURLSession uploadTask 封装了请求的 httpBody 属性。

于 2016-10-19T20:17:16.070 回答