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

How to get progress of file upload without multipart?

我正在 swift 中借助 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:) 委托方法。为此,您需要创建自己的会话并设置其委托。

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

这是您的 do 块中的更新代码:

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
}