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

前端 未结 2 1087
礼貌的吻别
礼貌的吻别 2021-02-19 01:58

I am trying to upload a video / image file using- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL; method using m

相关标签:
2条回答
  • 2021-02-19 02:20

    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")
    
    0 讨论(0)
  • 2021-02-19 02:47

    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.

    0 讨论(0)
提交回复
热议问题