简体   繁体   中英

How to get progress of file upload without multipart?

I am uploading file in swift with the help of URLSession. But issue is I don't get progress for the upload. I am not using any multipart request. I am just sending data of video in body of request.

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{
}

Please tell me how can I get the progress of how many bytes have been uploaded?

You need to implement the urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) delegate method. And to do this, you need to create your own session and set its delegate.

You should also use an upload task. This avoids the need to load the file into memory.

Here's the updated code inside your 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()

Then add:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM