包含0个mime部分的无效多部分请求Swift

时间:2015-05-19 05:13:16

标签: swift ios8 multipartform-data

我正在尝试通过Swift中的POST请求上传图片。

这是我的代码:

func uploadImagesToRamdomURL(server_url:String){
    let imageData = UIImageJPEGRepresentation(myImageView.image, 0.9)

    let url = NSURL(string:server_url)
    println(url)
    var request = NSMutableURLRequest(URL: url!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    var boundary = "---------------------------14737809831466499882746641449"

    let contentType = "multipart/form-data; boundary=\(boundary)"
    request.setValue(contentType, forHTTPHeaderField:"Content-Type")
    request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")

    println(request.allHTTPHeaderFields)

    var body = NSMutableData()

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

    body.appendData(imageData)
    //body.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


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

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

    println("returnString \(returnString)")

}

我搜索过&添加了上传所需的所有内容。

但是是什么让它给我错误“0部分mime部分的无效多部分请求。”

提前致谢。

0 个答案:

没有答案