通过Swift使用multipart/form-data将文件发送到服务器的步骤如下:
let boundary = generateBoundary()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let body = createBody(with: fileURL, boundary: boundary)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
completion(error)
}
}
task.resume()
}
if let fileData = try? Data(contentsOf: fileURL) {
let fileName = fileURL.lastPathComponent
let mimeType = mimeTypeForFileURL(fileURL)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!)
body.append(fileData)
body.append("\r\n".data(using: .utf8)!)
}
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
return body
}
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
let mimeType = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimeType as String
}
return "application/octet-stream"
}
uploadFileToServer(fileURL: fileURL, serverURL: serverURL) { error in
if let error = error {
print("Error uploading file: \(error)")
} else {
print("File uploaded successfully")
}
}
这样,你就可以使用Swift将文件以multipart/form-data的形式发送到服务器了。请注意,这只是一个基本的示例,实际情况可能需要根据具体的服务器端要求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云