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
Code Block request.addValue("multipart/form-data; boundary=&", forHTTPHeaderField: "Content-Type") var body = "" body += "--&\r\n" body += "Content-Disposition:form-data; name=\"image\"" body += "\r\n\r\n\(base64Image ?? "")\r\n" body += "--&)--\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:
Code Block 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
Code Block
I tried to do as instructed which makes my body looks like this:You usually put Content-Disposition:form-data; name="field-name" as the part header for the text field.
Code Block body += "--\(boundary)\r\n" body += "Content-Disposition:form-data; name=\"image\"" body += "\r\n\r\n\(base64Image ?? "")\r\n" body += "Content-Disposition:form-data; name=\"title\"" body += "\r\n\r\n\(name)\r\n" body += "--\(boundary)--\r\n"
The request still works but the title of the picture is not defined
I think I did not mention it but the request I'm trying to use is the post image from the Imgur API
Edit: Also tried adding a boundary between to have something like this:https://apidocs.imgur.com/#de179b6a-3eda-4406-a8d7-1fb06c17cb9c
Code Block 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"
but this is still not working
Edit2:
Had to change the way of putting the boundary to something like this:
Code Block body += "--\(boundary)\r\n"
which makes the body look like this:
Code Block 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 is now working
Thanks again for your help and the time you took to answer my questions !