如何在 Swift 4 中通过具有多个参数的多部分表单数据上传图像或文件

How to upload image or file through multipart form data with multi parameters in Swift4

我在通过图像选择器控制器上传图片或文件时遇到问题。我通过图像选择器选择图像,然后传递参数 event_id、booking_id、memeber_id 和 upfile。所有这些值在 Postman 中都是表单数据格式。如何将这些值发送到 API?在 postman 中,它是 运行ning 完美,但在 Xcode 中它显示错误。我在考虑参数,我发送的错误包含。

func UploadRequest() {
    let x: Int = defaults.integer(forKey: "ObjectID")
    user_id = String(x)
    auth_key = defaults.value(forKey: "AuthKey") as! String
    var request2 = URLRequest(url: uploadDoc! as URL)
    request2.httpMethod = "POST"

    //define the multipart request type
    if (self.img.image == nil) {
        return
    }
    let image_data = UIImageJPEGRepresentation(self.img.image!, 1)
    if(image_data == nil) {
        return
    }
    let boundry = generateBoundaryString()
    request2.setValue(user_id, forHTTPHeaderField: "user_id")
    request2.setValue(auth_key, forHTTPHeaderField: "auth_key")
    request2.setValue("multipart/form-data; boundary=\(boundry)", forHTTPHeaderField: "Content-Type")
    let param = ["event_id":evId,"booking_id":receivedId,"member_id":memId]
    print(param)
    request2.httpBody = createBody(params: param, filePathKey: "upfile", imageDatakey: image_data! as NSData, boundary: boundry) as Data
    self.jsonDifferentRunDoc(passString: request2)
}

//Generate Boundry String
func generateBoundaryString() -> String {
    return "Boundary-\(UUID().uuidString)"
}

func createBody(params: [String: String]?, filePathKey: String, imageDatakey: NSData, boundary: String) -> NSData {
    let body = NSMutableData()
    if params != nil {
        for (key, value) in params! {
            body.appendString(boundary)
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    let filename = "jk.jpg"
    let mimetype = "image/jpg"

    body.appendString(boundary)
    body.appendString("Content-Disposition: form-data; name=\"upfile\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDatakey as Data)
    body.appendString("\r\n")
    body.appendString("--".appending(boundary.appending("--")))

    //print("Body = \(body)")
    return body
}

我运行这个函数时显示错误。

上传边界时出现语法错误:

lineBreak = "\r\n";
body.appendString("--\(boundary)--\(lineBreak)");

请试试这个。