ios - URLSession dataTask / uploadTask splitting large uploads into multiple requests
问题描述
Hoping someone can shed some light on this behavior.
- Large file (say 50mb+) needs to be uploaded to server
- Uploading is split into multiple requests, not chunks in a single request ( see Charles image )
- Using any of these all have the same behavior.
URLSession.shared.dataTask
URLSession.shared.uploadTask
URLSession.shared.uploadTask(withStreamedRequest:)
URLSession.shared.dataTaskPublisher
- 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 ).
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
解决方案
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.
推荐阅读
- android - Android 无法序列化 Kotlin lambda
- python - Python发布请求,发布问题
- html - 使用 css 创建无限循环
- javascript - 在Javascript中更改构造函数类中属性的默认值
- jquery - Phpstorm 警告字符串不可分配给参数类型
- c# - 如何使用 LINQ 从似乎存储在字符串中的 JObjects 数组中访问特定值
- c++ - 使用 toInt 将子字符串转换为整数
- c# - 在 SQL Server 的一个 Entity Framework Core 查询中使用多个大型数据库?
- javascript - 使用带有graphql的react hooks时,按钮元素中的onClick不会触发react-table中的重新渲染
- google-api - 需要帮助 - 将 Google 我的商家帖子嵌入网站