How to upload zip file to server with MultipartFor

2019-06-09 23:17发布

I am trying to upload a zipfile to the server. When i tried to upload a zip file to the server, File is not getting uploaded successfully. I am getting error from the server. At the server side userid is separated from the file name.

The actual server JSON response is:

{"error":{"login":"Sorry,Failed to Login "}}

I am new to multipart/form-data, so I don't know the cause behind this issue. This is my code:

func uploadData() {
    let headers: HTTPHeaders = [
        "Content-type": "multipart/form-data"
    ]

    var username:String = username_textfield.text!
    var password:String = password_textfield.text!

    let fileManager = FileManager()

    let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("/cropsapdb_up_\(useridsaved).zip")
    var filepath = paths

    var sourceURL = URL(fileURLWithPath: filepath)
    var zipnewdata:NSData = NSData()

    zipnewdata = FileManager.default.contents(atPath: filepath) as! NSData

    let parameters = ["unm2": username,"pass2":password,"ufile":filepath]

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append( zipData, withName: "cropsapdb_up_\(self.useridsaved)", fileName: "cropsapdb_up_\(self.useridsaved).zip", mimeType: "application/zip")
        for (key, value) in parameters {
            multipartFormData.append((value.data(using: String.Encoding.utf8)!), withName: key)
        }
    }, usingThreshold: UInt64.init(), to: "myurl", method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("Succesfully uploaded = \(response.data)")
                if let JSON = response.result.value
                {
                    print("JSON: \(JSON)")
                }
                if let err = response.error{
                    print("response error")
                    return
                }

            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")

        }
    }
}

0条回答
登录 后发表回答