unable to upload file using NSURLSession multi-part form data in iOS

被刻印的时光 ゝ 提交于 2019-12-04 00:04:11

You aren't uploading what you think you are. Your intent is for the body data to be uploaded as-is. Instead, when you call uploadTaskWithRequest:fromFile:, that method effectively nils out any HTTPBody or HTTPBodyStream values in the request and replaces them with the contents of the URL that you passed in via the fromFile: parameter.

So unless you're writing that block of form-encoded body data to that file URL somewhere else, you're uploading the file by itself instead of the multipart form data.

You need to tweak your code to write the form data out to a file instead of storing it in HTTPBody, then pass the URL of that file to the fromFile: parameter.

To prevent wasting time dealing with it.

The complete snippet based on @dgatwood answer

private func http(request: URLRequest){
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue: .main)
        /*Tweaking*/
        let task = session.uploadTask(with: request, from: request.httpBody!)
        task.resume()
    }

And.. do not forget to add the Headers on request object like

request.setValue("multipart/form-data; boundary=\(yourboundary)", forHTTPHeaderField: "Content-Type")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!