在swift中使用HTTP POST发送文本和图像

时间:2016-06-27 10:50:21

标签: php ios xcode swift http-post

我正在尝试通过HTTP POST将带有文本消息的图像上传到php服务器,但发送的消息到达服务器为null

@IBOutlet var image: UIImageView!
var CUSTOMER_KEY = "dkeqnq9fmkhq"
var msg = "The first msg"

override func viewDidLoad() {
    super.viewDidLoad()

}


@IBAction func selectVideo(sender: AnyObject) {

    var videoPickerController = UIImagePickerController()
    videoPickerController.delegate = self

    videoPickerController.sourceType = .SavedPhotosAlbum
    videoPickerController.mediaTypes =  [kUTTypeMovie as String]



    self.presentViewController(videoPickerController, animated: true, completion: nil)
}
@IBAction func selectPicture(sender: AnyObject) {

    let ImagePicker = UIImagePickerController()
    ImagePicker.delegate = self
    ImagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

    self.presentViewController(ImagePicker, animated: true, completion: nil)


}



func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    image.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    self.dismissViewControllerAnimated(true, completion: nil)
}



@IBAction func upload_request(sender: AnyObject) {
    UploadRequest()
}



func UploadRequest()
{
    let comURL = "myurlhere?customer_key=dkeqnq9fmkhq&msg=MSGHere"


    let sendURL:NSURL = NSURL(string: comURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!




    let request = NSMutableURLRequest(URL: sendURL)

    request.HTTPMethod = "POST"



    let boundary = generateBoundaryString()


    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    if (image.image == nil)
    {
        return
    }

    let image_data = UIImagePNGRepresentation(image.image!)


    if(image_data == nil)
    {
        return
    }


    let body = NSMutableData()

    let newRandomName = randomStringWithLength(32)
    let fname = (newRandomName as String) + ".png"
    let mimetype = "image/png"



    print ("New File Name:" + (newRandomName as String))

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(image_data!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



    request.HTTPBody = body



    let session = NSURLSession.sharedSession()


    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        print(dataString)

    }

    task.resume()


}


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

func randomStringWithLength (len : Int) -> NSString {

    let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

    var randomString : NSMutableString = NSMutableString(capacity: len)

    for (var i=0; i < len; i++){
        var length = UInt32 (letters.length)
        var rand = arc4random_uniform(length)
        randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
    }

    return randomString
}

另外如果我想同时发送图像,视频和短信同样如何做到这一点,我选择它后采取视频路径并通过HTTP POST上传到服务器?

3 个答案:

答案 0 :(得分:0)

对所有类型的请求使用Alamofire框架。它简单易实现

Alamofire.upload(.POST, requestURL, headers: nil, multipartFormData: { multipartFormData in

        if image != nil
        {
            if let imageData = UIImageJPEGRepresentation(image!, 1)
            {
                multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "profile.jpg", mimeType: "image/jpeg")
            }
        }

        for (key, value) in params
        {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }
        },

        encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    success(response: response.result.value)
                }
            case .Failure(let error):
                failure(error: error)
            }
    })

答案 1 :(得分:0)

使用Alamofire,然后将此类用作请求管理器。来自this answer

urlRequestWithComponents函数引用
class MultiFormRequest {

        private func urlRequestWithComponents(url:NSURL, parameters:[String:AnyObject], imageData:(key:String,data:NSData)?) -> (URLRequestConvertible, NSData) {

            // create url request to send
            let mutableURLRequest = NSMutableURLRequest(URL: url)
            mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
            let boundaryConstant = "myRandomBoundary12345";
            let contentType = "multipart/form-data;boundary="+boundaryConstant
            mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")

            // create upload data to send
            let uploadData = NSMutableData()

            if let imageData = imageData {
                // add image
                uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
                uploadData.appendData("Content-Disposition: form-data; name=\"\(imageData.key)\"; filename=\"\(imageData.key).jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
                uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
                uploadData.appendData(imageData.data)
            }
            // add parameters
            for (key, value) in parameters {
                uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
                uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
            }
            uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



            // return URLRequestConvertible and NSData
            return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
        }

        func requestWithParams(url:NSURL,
                               paramsDic:[String:AnyObject],
                               imageData:(key:String,data:NSData)?,
                               succesBlock:((result:AnyObject?)->Void)?,
                               failBlock:((error:NSError?)->Void)?)  {


            let urlRequest = urlRequestWithComponents(url, parameters: paramsDic, imageData: imageData)
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true

            Alamofire.upload(urlRequest.0, data: urlRequest.1)
                .responseJSON(completionHandler: { (response) in
                    UIApplication.sharedApplication().networkActivityIndicatorVisible = false

                    switch response.result {
                    case .Success:
                        succesBlock?(result:response.result.value)

                    case .Failure:
                        failBlock?(error:response.result.error)
                    }

                })
        }
    }

答案 2 :(得分:0)

您可以轻松地将文本发送到服务器,如下所示:

  func sendText () {

    var url:String = "Your url"

    var param = ["name": self.nameTextField.text!, "otherparameter":self.otherparameterTextField.text!, "otherparameter2":self.otherparameter2TextField.text!]

    Alamofire.request(.POST, url , parameters: param).responseJSON { response in

        if let data = response.result.value {

            print(data)
        }

    }

}