首页 > 解决方案 > URLSession dataTask / uploadTask splitting large uploads into multiple requests

问题描述

Hoping someone can shed some light on this behavior.

  1. Large file (say 50mb+) needs to be uploaded to server
  2. Uploading is split into multiple requests, not chunks in a single request ( see Charles image )
  3. Using any of these all have the same behavior.
  1. Server is node / express, testing locally.
// Express server route
app.post('/save', (req, res, next) => {

   // Receives twice for the same upload
}

Example Attempt

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/octet-stream", forHTTPHeaderField: "content-type")
    request.setValue("chunked", forHTTPHeaderField: "transfer-encoding")
    request.httpBodyStream = InputStream(data: package)
    let task = self.session.uploadTask(withStreamedRequest: request)
    self.streamingTask = task
    task.resume()

Is this normal? It seems odd to me, and makes it difficult to put together the data at the end. I've set various headers to see if that's what I'm missing, such as Content-Length, tried multiple encodings ( multipart/form, json ).

Charles Image

Edit: Just discovered that Content-Length is a reserved header and cannot be manually set. But the content length is not being set to the size of the httpBody.

https://developer.apple.com/documentation/foundation/nsurlrequest

标签: iosnode.jsswiftuploadlarge-files

解决方案


I'd say that you should leave it as one upload request if possible and utilize background sessions to let the OS handle the upload for you.

https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1407496-background

Then you don't have to worry about one part failing to upload but others did, etc. It also simplifies things for your server, it either gets the file or it doesn't.


推荐阅读