NSURLSession multipart / form-data post request

时间:2016-06-25 12:28:45

标签: ios swift http multipartform-data nsurlsession

我在同一个帖子请求中向我的服务器发送文本和图片时遇到了一些麻烦。我认为问题与我设定边界的方式有关。

我使用swift和ios9。

我按照这里的说明ios Upload Image and Text using HTTP POST 尽我所能将obj-c转换为swift

然而,当我向我的服务器发布请求时,每当我尝试访问诸如$ _POST [“key”]之类的帖子数据时,我都会得到一个未定义的索引错误。这是我用来设置http请求的代码,任何人都可以发现错误:

 func sendRegisterRequest(params:Dictionary<String, String>, withImage image: UIImage) {

    // https://stackoverflow.com/questions/8564833/ios-upload-image-and-text-using-http-post
    let url = NSURL(string: "MY_URL");
    let request = NSMutableURLRequest(URL: url!)
    // the boundary string : a random string, that will not repeat in post data, to separate post data fields.
    let boundaryConstant = "----------V2ymHFg03ehbqgZCaKO6jy--";

    // string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
    let fileParamConstant = "file";

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


    // post body
    let body = NSMutableData();



    // add params (all params are strings)
    for (key, value) in params {
        body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
        body.appendData("Content-Disposition: form-data; name=\"\(key.stringByAddingPercentEncodingWithAllowedCharacters(.symbolCharacterSet())!)\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
        body.appendData("\(value.stringByAddingPercentEncodingWithAllowedCharacters(.symbolCharacterSet())!)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    }

    //print(body);
    // add image data
    let imageData = UIImageJPEGRepresentation(image, 1.0);

    body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData("Content-Disposition: form-data; name=\"\(fileParamConstant)\"; filename=\"image\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData(imageData!);
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);
    body.appendData("\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!);

    request.HTTPBody = body;

1 个答案:

答案 0 :(得分:1)

使用多部分表单数据时,必须在边界前面加上正文数据中的另外两个连字符,并且还必须在最后边界的末尾添加两个连字符。所以如果你有:

boundary=foo

那么身体应该是这样的:

--foo
field 1 info
--foo
field 2 info
--foo--

另见What is the '-' in multipart/form-data?