Alamofire
File Upload
Swift
iOS
HTTP `Parameters`

Uploading file with parameters using Alamofire

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When you need to upload a file and send extra form fields in the same request, the usual solution is multipart/form-data. In Alamofire, that means building a multipart body, appending the file data, then appending each parameter as its own form field.

Use Multipart Form Data for Files Plus Parameters

If the server expects a file and additional values such as userId, title, or description, a multipart upload is the right shape.

This example uploads an image plus two string parameters:

swift
1import Alamofire
2import Foundation
3
4let url = "https://example.com/upload"
5let imageURL = URL(fileURLWithPath: "/tmp/avatar.jpg")
6let parameters: [String: String] = [
7    "userId": "42",
8    "description": "Profile photo"
9]
10
11AF.upload(
12    multipartFormData: { multipartFormData in
13        multipartFormData.append(imageURL, withName: "file")
14
15        for (key, value) in parameters {
16            if let data = value.data(using: .utf8) {
17                multipartFormData.append(data, withName: key)
18            }
19        }
20    },
21    to: url,
22    method: .post
23)
24.responseString { response in
25    switch response.result {
26    case .success(let body):
27        print("Upload succeeded:", body)
28    case .failure(let error):
29        print("Upload failed:", error)
30    }
31}

Each parameter becomes a separate form field in the same multipart request. That is different from JSON-encoding the parameters into the body.

Add File Name and MIME Type Explicitly When Needed

Some APIs require an explicit file name and MIME type. In that case, upload raw data instead of appending the file URL directly.

swift
1import Alamofire
2import Foundation
3
4let fileData = try Data(contentsOf: imageURL)
5
6AF.upload(
7    multipartFormData: { multipartFormData in
8        multipartFormData.append(
9            fileData,
10            withName: "file",
11            fileName: "avatar.jpg",
12            mimeType: "image/jpeg"
13        )
14
15        multipartFormData.append(Data("42".utf8), withName: "userId")
16        multipartFormData.append(Data("Profile photo".utf8), withName: "description")
17    },
18    to: url,
19    method: .post
20)
21.uploadProgress { progress in
22    print("Progress:", progress.fractionCompleted)
23}
24.responseDecodable(of: UploadResponse.self) { response in
25    print(response)
26}
27
28struct UploadResponse: Decodable {
29    let id: String
30    let status: String
31}

This form is more explicit and often easier to align with backend API contracts.

Match Field Names to the Server Contract

The most important detail is not Alamofire syntax. It is making sure the form field names match what the server expects. If the backend expects image, but the client sends file, the upload may fail even though the HTTP request itself is well-formed.

Typical fields include:

  • The binary file part, such as file or image
  • Metadata fields, such as userId or category
  • Authentication headers outside the multipart body

If the server expects a bearer token, add it through HTTP headers instead of embedding it as a form parameter.

swift
let headers: HTTPHeaders = [
    "Authorization": "Bearer some-token"
]

Common Pitfalls

One common mistake is trying to send the file in a normal parameters dictionary. Files are binary payloads and need multipart encoding, not simple URL encoding or JSON encoding.

Another issue is using the wrong field name, MIME type, or file name. The request may technically succeed while the server rejects the uploaded part because it does not match the API contract.

Developers also sometimes forget to convert string parameters into Data before appending them to the multipart form. Alamofire's multipart builder expects Data or file URLs for each appended part.

Finally, do not assume every upload endpoint wants multipart form data. Some APIs accept raw binary uploads or pre-signed URLs instead. Use multipart only when the server contract calls for it.

Summary

  • Use multipart/form-data when uploading a file together with additional parameters.
  • Append each form field separately inside Alamofire's multipartFormData builder.
  • Provide fileName and mimeType explicitly when the server requires them.
  • Match field names and headers exactly to the backend API contract.
  • Do not try to send binary files through a normal parameters dictionary.

Course illustration
Course illustration

All Rights Reserved.