Swift - multipart / form-data - 如何定义边界/填充HTML正文?

时间:2015-04-10 09:24:51

标签: html ios swift request boundary

我正在尝试在Swift中为multipart / form-data-request定义边界。我的问题是如何在Swift中定义这个边界(最有效的方式)。我想发送一个包含ID和名称等数据的请求。

实际状态:

 let url = NSURL(string: "http://test.bla")
 let request = NSMutableURLRequest(URL: url!)

 // Set HTTPMethod for actual request
 request.HTTPMethod = "POST"

实际问题:

  • 如何定义边界
  • 如何使用必要的数据填充html正文

1 个答案:

答案 0 :(得分:3)

这是上传图片的代码需要定义边界

    var TWITTERFON_FORM_BOUNDARY:String = "AaB03x"
    let url = NSURL(string: url)!
    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10)
    var MPboundary:String = "--\(TWITTERFON_FORM_BOUNDARY)"
    var endMPboundary:String = "\(MPboundary)--"
    var data:NSData = UIImagePNGRepresentation(image)
    var body:NSMutableString = NSMutableString();
    // params
    if parameters != nil {
        for (key, value) in parameters! {
            body.appendFormat("\(MPboundary)\r\n")
            body.appendFormat("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendFormat("\(value)\r\n")
        }
    }
    // image upload
    body.appendFormat("%@\r\n",MPboundary)
    body.appendFormat("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"pen111.png\"\r\n")
    body.appendFormat("Content-Type: image/png\r\n\r\n")
    var end:String = "\r\n\(endMPboundary)"
    var myRequestData:NSMutableData = NSMutableData();
    myRequestData.appendData(body.dataUsingEncoding(NSUTF8StringEncoding)!)
    myRequestData.appendData(data)
    myRequestData.appendData(end.dataUsingEncoding(NSUTF8StringEncoding)!)
    var content:String = "multipart/form-data; boundary=\(TWITTERFON_FORM_BOUNDARY)"
    request.setValue(content, forHTTPHeaderField: "Content-Type")
    request.setValue("\(myRequestData.length)", forHTTPHeaderField: "Content-Length")
    request.HTTPBody = myRequestData
    request.HTTPMethod = "POST"
    .........