来自网络编程世界,我对使用多部分表单请求上传文件非常满意。但是,在iOS中,我们有一个名为 NSURLSession 的东西,方法是 uploadTaskWithRequest ,这似乎是要调用的方法做图像上传等。
Coming from the world of web programming, I'm pretty much comfortable with working with multipart form requests to upload files. However, in iOS, we have a thing called NSURLSession with the method uploadTaskWithRequest, which seems to be the method to call to do image uploads and the likes.
你能解释两种方法之间的区别吗,多部分表格上传 vs uploadTaskWithRequest ?如果我已经有一个处理多部分表单上传的后端,我可能需要进行哪种调整以便它还支持 uploadTaskWithRequest ?
Can you explain the difference between the two approach, multipart form upload vs uploadTaskWithRequest? If I already have a backend that handle multipart form uploads, what kind of adjustments that I might need so that it support uploadTaskWithRequest as well?
推荐答案uploadTaskWithRequest 只需发送 NSData ,文件,或作为请求的主体流。它没有做任何事情。它只是具有可以与后台会话一起使用的好处。
The uploadTaskWithRequest simply sends the NSData, file, or stream as the body of the request. It doesn't do anything beyond that. It simply has the benefit that it can be used with background sessions.
因此,如果您的Web服务需要 multipart / form-data 请求,您必须自己构建该请求(除非您使用AFNetworking或Alamofire之类的东西为您执行此操作)。一旦构建了该请求,就可以使用 dataTaskWithRequest (已设置 HTTPBody NSMutableURLRequest )或 uploadTaskWithRequest (在这种情况下,您不设置 HTTPBody ,而是将其作为参数提供给 uploadTaskWithRequest )。
So, if you have web service that is expecting multipart/form-data request, you have to build that request yourself (unless you use something like AFNetworking or Alamofire to do this for you). Once you've built that request, you can either use dataTaskWithRequest (having set the HTTPBody of the NSMutableURLRequest) or uploadTaskWithRequest (in which case you don't set HTTPBody, but rather provide it as a parameter to uploadTaskWithRequest).
顺便说一下,像 Charles 在这些情况下非常有用,让您可以观察幕后发生的事情。
By the way, a tool like Charles is very useful in these cases, letting you observe what's going on behind the scenes.
更多推荐
多部分表单上载和NSURLSession.uploadTaskWithRequest之间的区别
发布评论