如何在Swift4中通过多参数的多部分表单数据上传图像或文件

时间:2017-12-27 07:28:28

标签: ios swift uiimagepickercontroller multipartform-data nsurlsession

我在通过图像选择器控制器上传图片或文件时遇到问题。我通过图像选择器选择了图像,然后传递参数event_id,booking_id,memeber_id和upfile。所有这些值都是Postman中的表单数据格式。如何将这些值发送给API?在邮递员中,它运行得很好,但在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
}

运行此功能时显示错误。

1 个答案:

答案 0 :(得分:1)

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

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

请试一试。