如何在Web服务swift中将图像作为POST发送

时间:2016-01-20 06:48:35

标签: ios swift post

    var urlString = ""

    let url = NSURL(string: urlString)

    let theRequest = NSMutableURLRequest(URL: url!)

    theRequest.HTTPMethod = "POST"

    let parameters = []

    var err:NSError!

    do{
        theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
    }

    catch let error as NSError{

        err = error
        theRequest.HTTPBody = nil

    }

    theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    theRequest.addValue("application/json", forHTTPHeaderField: "Accept")

我在这里使用第三方类库进行签名。如何以图像的形式将其发布到webservices?

2 个答案:

答案 0 :(得分:2)

简单的例子:

//create session
var urlSession : NSURLSession!

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
urlSession = NSURLSession(configuration: configuration)

func updateUserDetails(image : UIImage? , dictUserDetails: [String: String?] ,completionClosure: (repos :NSDictionary) ->())  {

    let request = NSMutableURLRequest(URL: NSURL(string:"Your URL" )!)
    request.HTTPMethod = "POST"
    let boundary = generateBoundaryString()

    let token = getUserToken() as String
    request.addValue("Token " + token, forHTTPHeaderField: "Authorization") // add token if you need
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    guard image != nil else {
        request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: nil, boundary: boundary)

        let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            if (error != nil) {
                print(error!.localizedDescription)
            }

            if (data != nil) {
                if let jsonResult: NSDictionary  = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
                {
                    completionClosure(repos: jsonResult)
                }
                else
                {
                    completionClosure(repos: NSDictionary())
                }
            } else {
                completionClosure(repos: NSDictionary())
            }

        })
        postDataTask.resume()

        return
    }

    let imageData = UIImageJPEGRepresentation(image!, 0.3)

    request.HTTPBody = createBodyWithParameters(dictUserDetails, filePathKey: "profile_pic", imageDataKey: imageData, boundary: boundary)

    let postDataTask = self.urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

        if (error != nil) {
            print(error!.localizedDescription)
        }

        if (data != nil) {
            if let jsonResult: NSDictionary  = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as? NSDictionary
            {
                completionClosure(repos: jsonResult)
            }
            else
            {
                completionClosure(repos: NSDictionary())
            }
        } else {
            completionClosure(repos: NSDictionary())
        }

    })
    postDataTask.resume()
}

助手功能:

//Generate boundary
func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

//create body
func createBodyWithParameters(parameters: [String: String?]?, filePathKey: String?, imageDataKey: NSData?, boundary: String) -> NSData {
    let body = NSMutableData()

    if parameters != nil {

        for (key, value) in parameters! {

            if value != nil {

                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value!)\r\n")
            }
        }
    }

    if imageDataKey != nil
    {
        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey!)
        body.appendString("\r\n")

        body.appendString("--\(boundary)--\r\n")
    }

    return body
}

现在你可以这样使用它:

updateUserDetails(yourImage, dictUserDetails: [

                    //parameters example
                    "date_of_birth": birthDate,
                    "first_name": firstName,
                    "last_name" : lastName,
                    "email" : email,
                    "phone_number" : phoneNumber,
                    "address" : address,
                    "martial_status" : userMaritialStatus

                    ], completionClosure: { (repos) -> () in

                        print(repos)


                })

希望它会有所帮助。

答案 1 :(得分:1)

您没有说明您使用的是哪个第三方库,因此您可以使用此代码使用Alamofire

Alamofire.upload(
    .POST,
    "your_API_URL_here",
    multipartFormData: { multipartFormData in
        if let _ = image {
            if let imageData = UIImageJPEGRepresentation(image!, 1.0) {
                multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
            } else {
                print(image)
            }
        }
    }, encodingCompletion: {
        encodingResult in

            switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON { response in
                        switch response.result {
                            case .Success:
                                print("Success")
                            case .Failure(let error):
                                print(error)
                            }
                        }
                case .Failure(let encodingError):
                    print(encodingError)
                }
            }
        )
    }
} catch _ {

}