How send post data with text parameter and image f

2019-08-14 07:34发布

问题:

I make an application that allows user to upload image and several to our server. If I just post text data my code successfully post data to the server but when I try to post text data with image data, my server throw an exception.

here is my code:

class func Enroll(image: UIImage, date: String, studentid: String, guardianid:String, type:String){
    //date,student_id,type,guardian_id,image, type

    var textBody : String?
    let imageData = UIImagePNGRepresentation(image)

    let boundary = NSString(format: "---------------------------14737809831466499882746641449")
    let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
    let URL: NSURL = NSURL(string: "http://api-cc.appsence.net/v1/signs")!

    let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"

    let body : NSMutableData = NSMutableData()

    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData!)
    body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

    //fill text value here
    textBody = "date=\(date)&student_id=\(studentid)&guardian_id=\(guardianid)&type=\(type)"

    print("text body : \(textBody!)")
    let bodyTextData = textBody!.dataUsingEncoding(NSUTF8StringEncoding);
    body.appendData(bodyTextData!)
    request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
    // if data string use data using encoding

    request.HTTPBody = body

    NSURLSession.sharedSession().dataTaskWithRequest(request){ (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        if error == nil{

            print("sukses : \(NSString(data: data!, encoding: NSUTF8StringEncoding)!)")

        }else{

            print("ini error save \(NSString(data: data!, encoding: NSUTF8StringEncoding)!)")

        }


    }.resume()

}

How can I fix this issue?

回答1:

Alamofire 3+

  // import Alamofire
  func uploadWithAlamofire() {
    let image = UIImage(named: "myPhoto")!

    // define parameters
    let parameters = [
      "hometown": "bodrum",
      "living": "izmir"
    ]

    // Begin upload
    Alamofire.upload(.POST, "upload_url",
      // define your headers here
      headers: ["Authorization": "auth_token"],
      multipartFormData: { multipartFormData in

        // import image to request
        if let imageData = UIImageJPEGRepresentation(image, 1) {
          multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "myImage.png", mimeType: "image/png")
        }

        // import parameters
        for (key, value) in parameters {
          multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }
      }, encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
      encodingCompletion: { encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
          upload.responseJSON { result in
            debugPrint(result)
          }
        case .Failure(let encodeError):
          print(encodeError)
        }
    })
  }


回答2:

In one of my app I did below approach to post an image to server.Below are objective C syntax. However you can the use same approach in swift

1) convert the image to base 64 string NSData *imageData = UIImageJPEGRepresentation(<#UIImage * _Nonnull image#>, <#CGFloat compressionQuality#>); NSString *base64String = [imageData base64EncodedStringWithOptions:0];

2) Create a dictionary and add the base 64 string to dictionary

NSMutableDictionary *imagedict =[[NSMutableDictionary alloc] init];

    [imagedict setObject:base64String forKey:@"image"];

3) convert to json and use nsurl session to post it to your server
NSData * incidentData = [NSJSONSerialization dataWithJSONObject:imagedict options:0 error:&err];

4) Your server will receive the request as json and parse it to get the image and convert the base 64 string back to image