Created
January 30, 2023 12:32
-
-
Save dedeexe/fbb6c39ae9706c73445060974968b026 to your computer and use it in GitHub Desktop.
A basic showing multipart/form-data implementation using 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
import UIKit | |
import Foundation | |
let image = UIImage(named: "example.jpg") | |
let imageData = image!.jpegData(compressionQuality: 0.75) | |
let date = Date() | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd" | |
let dateString = dateFormatter.string(from: date) | |
let url = URL(string: "https://example.com/upload")! | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
let boundary = "Boundary-\(UUID().uuidString)" | |
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") | |
var data = Data() | |
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) | |
data.append("Content-Disposition: form-data; name=\"image\"; filename=\"example.jpg\"\r\n".data(using: .utf8)!) | |
data.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!) | |
data.append(imageData!) | |
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) | |
data.append("Content-Disposition: form-data; name=\"name\"\r\n\r\n".data(using: .utf8)!) | |
data.append("example".data(using: .utf8)!) | |
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) | |
data.append("Content-Disposition: form-data; name=\"date\"\r\n\r\n".data(using: .utf8)!) | |
data.append(dateString.data(using: .utf8)!) | |
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) | |
request.httpBody = data | |
let task = URLSession.shared.dataTask(with: request) { data, response, error in | |
if let error = error { | |
print("error: \(error)") | |
return | |
} | |
if let response = response as? HTTPURLResponse { | |
print("statusCode: \(response.statusCode)") | |
} | |
if let data = data, let dataString = String(data: data, encoding: .utf8) { | |
print("data: \(dataString)") | |
} | |
} | |
task.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment