ios - Alamofire 文件上传出现错误 "JSON text did not start with array or object and option to allow fragments not set"

标签 ios swift http-post alamofire

下面是我的代码引用this question answer

func createRequest(ResumeID: String, CandidateID: String, MediaName: String, FileExtension : String, MediaType : String) throws -> URLRequest {

    let parameters = NSDictionary(objects: [ResumeID, CandidateID, MediaName, FileExtension,MediaType], forKeys: ["ResumeID" as NSCopying, "CandidateID" as NSCopying, "MediaName" as NSCopying, "FileExtension" as NSCopying, "MediaType" as NSCopying])

    let boundary = generateBoundaryString()

    let url = URL(string: "http://192.168.1.29/ColorsKit_New_Svr/WTCSvr.svc/WTCService?Id=6&SPName=Usp_RTN_IU_CandidateSubmissionResume")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let path1 = Bundle.main.path(forResource: "dummy-pdf_2", ofType: "pdf")!
    request.httpBody = try createBody(with: parameters as? [String : String], filePathKey: "MediaContent", paths: [path1], boundary: boundary)

    return request
}

private func createBody(with parameters: [String: String]?, filePathKey: String, paths: [String], boundary: String) throws -> Data {
    var body = Data()

    if parameters != nil {
        for (key, value) in parameters! {
            body.append("--\(boundary)\r\n")
            body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.append("\(value)\r\n")
        }
    }

    for path in paths {
        let url = URL(fileURLWithPath: path)
        let filename = url.lastPathComponent
        let data = try Data(contentsOf: url)
        let mimetype = mimeType(for: path)

        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n")
        body.append("Content-Type: \(mimetype)\r\n\r\n")
        body.append(data)
        body.append("\r\n")
    }

    body.append("--\(boundary)--\r\n")
    return body
}

func sendMultipartRequest() {
    let request: URLRequest

    do {
        request = try createRequest(ResumeID: "1", CandidateID: "1241124", MediaName: "dummy-pdf", FileExtension: "pdf", MediaType: "pdf")
    } catch {
        print(error)
        return
    }

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard error == nil else {
            // handle error here
            print(error!)
            return
        }

        // if response was JSON, then parse it

        do {                
            let responseDictionary = try JSONSerialization.jsonObject(with: data!)
            print("success == \(responseDictionary)")

            // note, if you want to update the UI, make sure to dispatch that to the main queue, e.g.:
            //
            // DispatchQueue.main.async {
            //     // update your UI and model objects here
            // }
        } catch {
            print(error)

            let responseString = String(data: data!, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
    }
    task.resume()
}

我得到的响应是:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} responseString = Optional("No Records Found")

这很奇怪,因为 Postman 给出了正确的响应。意味着代码中只缺少一些东西:(

enter image description here

最佳答案

使用 Alamofire

let upload_url = "your url"
let fieldName = "UploadedFile"
let mimeType = "plain/text"


Alamofire.upload(multipartFormData: { multipartFormData in

//you can add multiple file
        multipartFormData.append(fileData as Data, withName: fieldName, fileName: fileName, mimeType: mimeType)

    }, to: upload_url, method: .post, headers: ["Authorization": "auth_token"],

       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.response { [weak self] response in
                guard let _ = self else {
                    return
                }
                debugPrint(response)
            }
        case .failure(let encodingError):
            debugPrint("uploaderService error:\(encodingError)")
        }

    })

关于ios - Alamofire 文件上传出现错误 "JSON text did not start with array or object and option to allow fragments not set",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48220802/

相关文章:

ios - 由于缩放,使用 ImageView 进行人脸检测和缩放效果不佳?

ios - Locale 可以通过货币代码识别国家吗?

swift - 在 Swift 中编码/解码类的重要属性的方法

java - 所需的 MultipartFile 参数 'files' 不存在 - MultipartyEntityBuilder

iphone - 我应该使用哪种文件格式将数组保存到文件中?

iOS 在 -> CFRelease(iPhoneAddressBook) 处获取 exc-bad -access;

android - 如何在 Android 和 IOS 应用程序中正确显示来自 MySQL 数据库的选项卡(空格)?

ios - 科洛达委托(delegate) : fatal error: unexpectedly found nil while unwrapping an Optional value

Android:带参数的 Http post 不起作用

java - 编码 Android/Java 连接到 ASP.Net Web API