swiftrequestimgur

HttpBody request Swift


I'm actually trying to upload image to Imgur using its API.

I followed a tutorial and when it talks about the HttpBody tells to do something like

let boundary = "Boundary-\(UUID().uuidString)"
request.addValue("multipart/form-data; boundary=&", forHTTPHeaderField: "Content-Type")
var body = ""
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"image\""
body += "\r\n\r\n\(base64Image ?? "")\r\n"
body += "--\(boundary)--\r\n"
let postData = body.data(using: .utf8)
request.httpBody = postData

Which works perfectly fine but I don't understand how to add other variables to the body which is why after browsing on different StackOverflow questions I tried to do something on my own by setting the boundary as '&' and then just tried to do the following:

let bodyData = "image=\(base64Image ?? "")"
request.httpBody = bodyData.data(using: .utf8)

But I always end-up having server errors and I don't understand what I am doing wrong

Any help could be appreciated


Solution

  • Had to do a few things but managed to fill the body as I wanted:

    body += "--\(boundary)\r\n"
    body += "Content-Disposition:form-data; name=\"image\""
    body += "\r\n\r\n\(base64Image ?? "")\r\n"
    body += "--\(boundary)\r\n"
    body += "Content-Disposition:form-data; name=\"title\""
    body += "\r\n\r\n\(name)\r\n"
    body += "--\(boundary)--\r\n"
    

    Which makes the request works as expected and allow me to define a name for the picture I upload on Imgur