Here is the code for uploading a file using a POST request and form-data body type.
let contentType = "multipart/form-data; boundary=\(boundary)"
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
let fileName:String = String(request.fileURLForFormData!.path().split(separator: "/").last ?? "")
let fileData = try Data(contentsOf: request.fileURLForFormData!)
var uploadData = Data()
// Append file data
uploadData.append("--\(boundary)\r\n".data(using: .utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"image\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
uploadData.append("Content-Type: \(fileName.mimeType())\r\n\r\n".data(using: .utf8)!)
uploadData.append(fileData)
uploadData.append("\r\n".data(using: .utf8)!)
// Close the form data
uploadData.append("--\(boundary)--\r\n".data(using: .utf8)!)
// Set the request body
urlRequest.httpBody = uploadData
let (data, response) = try await URLSession.shared.upload(for: urlRequest, from: Data(contentsOf: request.fileURLForFormData!))
return .success((data, response))
Here is the error i am getting using data, dataTask, upload and uploadTask.
The request of a upload task should not contain a body or a body stream, use upload(for:fromFile:), upload(for:from:), or supply the body stream through the urlSession(_:needNewBodyStreamForTask:) delegate method.
When you create an upload request, the parameter you pass as
data:gets sent as the request body. To the body data you'd actually be sending right now is the raw file data, not the form-encoded data.And the API also complains because you shouldn't be setting the body on the request at all.
To fix this:
from:parameter when creating the request instead of passing the contents of the file on disk.urlRequest.httpBody.