Created
October 4, 2020 22:20
-
-
Save codecat15/6c1eaa5b7ea48b26b10d907fef68abf2 to your computer and use it in GitHub Desktop.
Upload image using multi-part form data in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// UploadImageDemo | |
// | |
// Created by CodeCat15 on 9/22/20. | |
// | |
import UIKit | |
struct ImageResponse: Decodable | |
{ | |
let status: Int? | |
let message: String? | |
} | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view. | |
UploadImage() | |
} | |
func UploadImage(){ | |
// your image from Image picker, as of now I am picking image from the bundle | |
let image = UIImage(named: "myimg.jpg",in: Bundle(for: type(of:self)),compatibleWith: nil) | |
let imageData = image?.jpegData(compressionQuality: 0.7) | |
let url = "YOUR_UPLOAD_IMAGE_URL" | |
var urlRequest = URLRequest(url: URL(string: url)!) | |
urlRequest.httpMethod = "post" | |
let bodyBoundary = "--------------------------\(UUID().uuidString)" | |
urlRequest.addValue("multipart/form-data; boundary=\(bodyBoundary)", forHTTPHeaderField: "Content-Type") | |
//attachmentKey is the api parameter name for your image do ask the API developer for this | |
// file name is the name which you want to give to the file | |
let requestData = createRequestBody(imageData: imageData!, boundary: bodyBoundary, attachmentKey: "profilePicture", fileName: "myTestImage.jpg") | |
urlRequest.addValue("\(requestData.count)", forHTTPHeaderField: "content-length") | |
urlRequest.httpBody = requestData | |
URLSession.shared.dataTask(with: urlRequest) { (data, httpUrlResponse, error) in | |
if(error == nil && data != nil && data?.count != 0){ | |
do { | |
let response = try JSONDecoder().decode(ImageResponse.self, from: data!) | |
print(response) | |
} | |
catch let decodingError { | |
debugPrint(decodingError) | |
} | |
} | |
}.resume() | |
} | |
func createRequestBody(imageData: Data, boundary: String, attachmentKey: String, fileName: String) -> Data{ | |
let lineBreak = "\r\n" | |
var requestBody = Data() | |
requestBody.append("\(lineBreak)--\(boundary + lineBreak)" .data(using: .utf8)!) | |
requestBody.append("Content-Disposition: form-data; name=\"\(attachmentKey)\"; filename=\"\(fileName)\"\(lineBreak)" .data(using: .utf8)!) | |
requestBody.append("Content-Type: image/jpeg \(lineBreak + lineBreak)" .data(using: .utf8)!) // you can change the type accordingly if you want to | |
requestBody.append(imageData) | |
requestBody.append("\(lineBreak)--\(boundary)--\(lineBreak)" .data(using: .utf8)!) | |
return requestBody | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment