如何添加额外的POST参数?

时间:2015-04-06 12:23:13

标签: ios swift post nsurlrequest

这是上传图片的代码,但是我必须发送另一个POST参数来知道谁是上传图片的人。

var request = NSMutableURLRequest(URL: NSURL(string:"https://www.theweb.com/api/img.php")!)

        request.HTTPMethod = "POST"

        var boundary = NSString(format: "---------------------------14737809831466499882746641449")
        var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
        //  println("Content Type \(contentType)")
        request.addValue(contentType, forHTTPHeaderField: "Content-Type")
        request.HTTPBody = dataMeData

        var body = NSMutableData.alloc()


        // Image
        body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(NSString(format:"Content-Disposition: form-data; name=\"userfile\"; filename=\"\(me)\"\\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)!)

        request.HTTPBody = body

        var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)

        var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)

        println("returnString \(returnString!)")

我试图添加以下内容:

body.appendData(thePersonWhoUpload) ---> in NSData encoding it in UTF8 but it doesn't work. 

所以最后一个问题是:如何发送包含名称的另一个POST参数?

2 个答案:

答案 0 :(得分:0)

尝试这种方式...仅在帖子正文中包含上传的人名。

NSString *post = [NSString stringWithFormat:@"UploadedBy=%@ &",username];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

postData.appendData(imageData);

body.appendData(imageData);

答案 1 :(得分:0)

你需要使用multipart / form-data来上传带参数
的图像  这是一个堆栈溢出链接Upload image with parameters in Swift

或者你可以使用像SwiftHTTP

这样的第三方库