gpt4 book ai didi

ios - 如何在没有多部分的情况下获取文件上传进度?

转载 作者:可可西里 更新时间:2023-11-01 00:55:22 24 4
gpt4 key购买 nike

我在 URLSession 的帮助下快速上传文件。但问题是我没有获得上传进度。我没有使用任何多部分请求。我只是在请求正文中发送视频数据。

let urlStr = UserDefaults.standard.value(forKey: "Resumable") as? String ?? ""
let url = URL(string: urlStr)

do{
var request = try URLRequest(url: url!, method: .put)
// request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
// request.setValue("300000", forHTTPHeaderField: "X-Upload-Content-Length")
request.setValue("video/*", forHTTPHeaderField: "Content-Type")
request.setValue("278", forHTTPHeaderField: "Content-Length")
request.timeoutInterval = 60.0

let path = Bundle.main.path(forResource: "video", ofType: "mov")
let videodata: NSData = NSData.dataWithContentsOfMappedFile(path!)! as! NSData

request.httpBody = videodata as Data

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.allHeaderFields)

if httpResponse.statusCode != 200 {
return
}else{
if let url = httpResponse.allHeaderFields["Location"] as? String{
}
}
}
})
task.resume()
}catch{
}

请告诉我如何获得上传了多少字节的进度?

最佳答案

您需要实现 urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) 委托(delegate)方法。为此,您需要创建自己的 session 并设置其委托(delegate)。

您还应该使用上传任务。这避免了将文件加载到内存中的需要。

这是 do block 中的更新代码:

var request = try URLRequest(url: url!)
// request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
// request.setValue("300000", forHTTPHeaderField: "X-Upload-Content-Length")
request.setValue("video/*", forHTTPHeaderField: "Content-Type")
request.setValue("278", forHTTPHeaderField: "Content-Length")
request.timeoutInterval = 60.0

let videoURL = Bundle.main.url(forResource: "video", withExtension: "mov")!

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
let task = session.uploadTask(with: request, fromFile: videoURL) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.allHeaderFields)

if httpResponse.statusCode != 200 {
return
}else{
if let url = httpResponse.allHeaderFields["Location"] as? String{
}
}
}
}
task.resume()

然后添加:

func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
// update progress as needed
}

关于ios - 如何在没有多部分的情况下获取文件上传进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50332397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com