在 Swift 中将多部分表单数据添加到 uploadTask(with:fromfile:)

OmO*_*ker 6 macos file-upload multipartform-data http-post swift

我正在尝试将文件(png、doc、jpg 等)发送到我的服务器。但是,为了正确保存文件,我想将文件扩展名添加到我的 POST 请求中。Apple.developer 说“忽略此请求对象中的正文流和正文数据。” 有没有办法将正文数据添加到我的请求中?这是我到目前为止所拥有的:

func uploadFile(filePath: String, endpoint: String) -> Void {

    let session = URLSession.shared
    let url = URL(string: endpoint)!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let fileUrl = URL(fileURLWithPath: filePath)

    let task = session.uploadTask(with: request, fromFile: fileUrl)
    task.resume()

}
Run Code Online (Sandbox Code Playgroud)

我尝试切换到使用 uploadTask(with:data:) 但我不确定如何将文件添加到数据,因为大多数示例都使用图像