1

I have to upload files on server using multipart request. For network calls i am using Alamofire.

What i have done so far is below

Request Service:
enter image description here

Multipart request:-

let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        let  fileData = Filedata() // getting data from local path

        let URL = try! URLRequest(url: "https://SomeUrl/upload", method: .post, headers: headers)
        Alamofire.upload(multipartFormData: { (multipartFormData) in

             //multipartFormData.append(fileData, withName: "image", fileName: "image", mimeType: "image/png")
               multipartFormData.append(fileData, withName: "file")

        }, with: URL, encodingCompletion: { (result) in

            switch result {
            case .success(let upload, _, _):

                upload.responseJSON { response in
                    print(response)
                }
            case .failure(let encodingError):
                print(encodingError)
            }

        })

Response:-

{ Status Code: 400, Headers {
    Connection =     (
        close
    );
    "Content-Type" =     (
        "application/json;charset=UTF-8"
    );
    Date =     (
        "Tue, 15 May 2018 10:34:15 GMT"
    );
    "Transfer-Encoding" =     (
        Identity
    );
} }
[Data]: 171 bytes
[Result]: SUCCESS: {
    error = "Bad Request";
    message = "Required request part 'file' is not present";
    path = "/files/safebolt.org/upload";
    status = 400;
    timestamp = "2018-05-15T10:34:15.715+0000";
}

Can anyone please tell me what i am doing wrong with request ?

aqsa arshad
  • 801
  • 8
  • 27

3 Answers3

2

I have created one function. Hope it works for you.

//Alamofire file upload code
func requestWith(URLString: String,
                 imageData: Data?,
                 fileName: String?,
                 pathExtension: String?,
                 parameters: [String : Any],
                 onView: UIView?,
                 vc: UIViewController,
                 completion:@escaping (Any?) -> Void,
                 failure: @escaping (Error?) -> Void) {

    let headers: HTTPHeaders = [
        "Content-type": "multipart/form-data"
    ]

    let URL = BASE_PATH + URLString
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        if let data = imageData {
            multipartFormData.append(data, withName: "fileUpload", fileName: "\(fileName!).\(pathExtension!)", mimeType: "\(fileName!)/\(pathExtension!)")
        }

    }, usingThreshold: UInt64.init(), to: URL, method: .post, headers: headers) { (result) in

        switch result {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if let err = response.error {
                    failure(err)
                    return
                }
                completion(response.result.value)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            failure(error)
        }
    }
}
Manish Mahajan
  • 2,062
  • 1
  • 13
  • 19
  • Mine is almost same as yours. Still i am getting the error of bad request. – aqsa arshad May 15 '18 at 10:54
  • What is status code, is it working in postman, is web method is right? – Manish Mahajan May 15 '18 at 10:56
  • How you are sending data? Somethign wrong in parameter passing – Manish Mahajan May 15 '18 at 11:27
  • What is that FileData()? is it Data Type? See my code var data: Data? = nil var fileName: String? = nil if targetListDeviceFilePath != nil { let path = targetListDeviceFilePath?.path data = FileManager.default.contents(atPath: path!) fileName = targetListDeviceFilePath?.lastPathComponent } I am picking file from file manager – Manish Mahajan May 15 '18 at 11:42
  • class func getFileData(path : String) -> Data { if (path.isFileExists()) { let fileURL = path.documentDirectoryPath() let data = try! Data(contentsOf: fileURL) return data } return Data() } – aqsa arshad May 15 '18 at 11:43
  • If picking from File Manager then try my code, and see if it works – Manish Mahajan May 15 '18 at 11:44
2

Try with:

multipartFormData.append(fileData, withName: "file", fileName: "file", mimeType: "image/png")
GreyHands
  • 1,734
  • 1
  • 18
  • 30
0

Try This, is an example it works for me. If you want to convert encode 64 for images add extension. If simply post the data and image this code may help.

//creating parameters for the post request

    let parameters: Parameters=[

        "ad_title":classText1.text!,
        "ad_description":classText2.text!,
        "ad_category":CategoryClass.text!,
        "ad_condition":classText3.text!,
        "ad_username":classText6.text!,
        "ad_usermobile":classText7.text!,
        "ad_city":classText8.text!,
        "ad_price":classText4.text!,
        "negotiable":classText5.text!,
        "image1":adImage1.image!,
        "image2":adImage2.image!,
        "image3":adImage3.image!,
        "image4":adImage4.image!


    ]
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }


    }, usingThreshold: UInt64.init(), to: URL, method: .post) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("Succesfully uploaded  = \(response)")
                if let err = response.error{

                    print(err)
                    return
                }

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

        }
    }
AzeTech
  • 623
  • 11
  • 21