简体   繁体   中英

Sending Image to server with parameters in Swift

I am trying to send Image on the server with json parameter using Alamofire. But on the server they are able to receive the image but not the Json i am sending. Below is the code that i am using:

let parameters: [String : String] = [
            "preferredVenueType": "club",
            "userId": "1"
        ]
let urlRequest = urlRequestWithComponents(baseURL + uploadImage, parameters: parameters , imageData: imageData!)
upload(urlRequest.0, data: urlRequest.1)
 .progress { (bytesWritten, totalBytesWritten,   totalBytesExpectedToWrite) in
 //print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
 }
.responseJSON {response in
                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")
 }




func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {

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

       // mutableURLRequest.HTTPBody = jsonData


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

        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"profileImage\"; filename=\"profileImage.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData)

        // 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("Content-Disposition: form-data; name=\"json\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

                        }
        uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



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

    }

I am getting error message in response as they are unable to receive the JSON data along with the image file.

I solved my Problem by sending parameters as a JSON String instead of key value pairs.

 let parameters: [String : String] = [
            "preferredVenueType": prameterText,
            "userId": userId,
        ]
         var theJSONText : NSString  = ""

        do {
            let theJSONData = try NSJSONSerialization.dataWithJSONObject(
                parameters ,
                options: NSJSONWritingOptions(rawValue: 0))
            theJSONText = NSString(data: theJSONData,
                encoding: NSASCIIStringEncoding)!
            // due to some reason NSUTF8StringEncoding was not working so i used ASCII encoding
        } catch let error as NSError {
            print(error)
        }

And while sending it to server i used

let uploadData = NSMutableData()

        uploadData.appendData("--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"json\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("\(theJSONText)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

After sending parameters as a JSON String the data was successfully uploaded to server.

Hi I don't have knowledge on swift. But according to your issue, the server receiving image that means url is correct. so

1) first check the data your sending. may be your sending wrong type of data. eg: server side {dictionary[dictionary]}, your sending{dictionary} like this.

2)check the header fields.

3)check the name of header field objects and keys.(capital or small) each and every letter.

4)finally add the below code in your project .plist files. Add to each and every plist in your project.

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
 </dict>

to add this, right click on .plist , then open it as source code.copy the above lines and past the lines before "</dict></plist>" at the end.

just try this.. I am not sure about this ,it will be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM