无法在swift中上传嵌套的multipart表单数据

时间:2015-11-26 13:50:54

标签: django swift django-rest-framework multipartform-data alamofire

大家好我在swift中上传嵌套的multipart表单数据时遇到问题我试图使用alamofire但它没有做我想要它做的事情:(。 我的服务器正在运行Django Rest Framework,只需上传一个Image和参数就可以正常运行,问题是上传带有嵌套图像和其他用户数据的用户数据。 因此,我认为我对嵌套表单的语法做错了 - 数据继承我正在运行的函数并且正在创建用户,但是服务器无法保存图像

func createUserWithImage(userName username: String, email: String, password: String, firstName: String, lastName: String, completion: UserHandler = nil) {
    var user: User? = nil
    defer { completion?(user) }

    let testField: String = "testoftestfield"
    let status: String = "test of status"
    let parameters = [
        "username": username,
        "email": email,
        "password": password,
        "first_name": firstName,
        "last_name": lastName,
    ]

    let image = UIImage(named: "ali.jpg")

    Alamofire.upload(.POST, Endpoint.RegisterUser.url, multipartFormData: {
        multipartFormData in

        if let _image = image {
            print("test1")
            if let imageData = UIImageJPEGRepresentation(_image, 0.5) {
                print("test2")
                multipartFormData.appendBodyPart(data: imageData, name: "profile[profileImage]", fileName: "profileImage.jpg", mimeType: "image/jpg")
            }
        }

        for (key, value) in parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }

        }, encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)

                    let json = JSON(upload)

                    print("The Upload is: " + json.description)
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
    })

}

那么有没有人知道如何发送嵌套的多部分表单数据?:)

1 个答案:

答案 0 :(得分:1)

func uploadImageWithFormedData() - > (){

  /* My URL:http://162.74.44.11/ImageApp/index.php/api/user/set_pic;

     Input Parameter :
   InputDict:
    {
        "user_id" = "1",
        "avtar" = "default",
        "picture" = "image.png"
    }

* /

    let BoundaryConstant  = "----------V2ymHFg03ehbqgZCaKO6jy";
    let FileParamConstant = "picture"

    let requestURL:URL = URL(string: "http://162.74.44.11/ImageApp/index.php/api/user/set_pic")! as URL

    var request : URLRequest = URLRequest (url: requestURL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30.0)
    request.httpMethod = "POST"
    request.httpShouldHandleCookies = false;
    let  contentType = "multipart/form-data; boundary=\(BoundaryConstant)"
    request.setValue(contentType, forHTTPHeaderField: "Content-Type")

//保存帖子参数的词典。您可以设置服务器接受或编程接受的帖子参数。

    var _params = [String:String]()

    _params.updateValue(user_id, forKey: "user_id")
    _params.updateValue("default", forKey: "avtar")

    var body:Data = Data()
    for (key,value) in _params
    {
        body.append("--\(BoundaryConstant)\r\n".data(using:String.Encoding.utf8)!)

        body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using:String.Encoding.utf8)!)

        body.append("\(value)\r\n".data(using:String.Encoding.utf8)!)


    }

    let imageData:Data? = UIImagePNGRepresentation(UIImage(named: "girl_greendotted_cloth")!)

    if imageData != nil {
        body.append("--\(BoundaryConstant)\r\n".data(using:String.Encoding.utf8)!)

        body.append("Content-Disposition: form-data; name=\"\(FileParamConstant)\"; filename=\"image.png\"\r\n".data(using:String.Encoding.utf8)!)

        body.append("Content-Type: image/jpeg\r\n\r\n".data(using:String.Encoding.utf8)!)

        body.append(imageData!)

        body.append("\r\n".data(using:String.Encoding.utf8)!)
    }

    body.append("--\(BoundaryConstant)--\r\n".data(using:String.Encoding.utf8)!)

    request.httpBody = body

    request.setValue("\(body.count)", forHTTPHeaderField: "Content-Length")

    let session = URLSession.shared
    let  task = session.dataTask(with: request, completionHandler: {(data,response,error) in


        if (data != nil)
        {
            do{
                let dict =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves)
                print(dict);
            }
            catch
            {

            }

        }

    }
    )

    task.resume()


     }