如何使用 URLSession 在多部分表单数据中发送音频文件? Swift

How to send audio file in Multipart form data using URLSession? Swift

我想使用 URLSession 从数据中发送一个 .m4a 格式的音频文件。目前,我已成功将音频文件发送到服务器,但在服务器端,我的音频文件未被识别为音频文件,那是因为我的扩展名 .m4a 未到达那里。在我这边,我检查了所有可能性,比如检查 mime 类型 'audio/m4a',我的音频 URL 以扩展名 m4a 结尾。但我无法解决问题。下面是我用来发送音频的代码。任何帮助将不胜感激。

guard let url = URL(string: "myURL") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = generateBoundary()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
let audioMedia = AudioMedia(audioWithURL: audioURL, forKey: "myKey")
let dataBody = createDataBody(withParameters: parameters,audio: audioMedia, boundary: boundary)
request.httpBody = dataBody
     
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
     if let data = data {
        do {
             let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]
                if let res = json?["res"] {
                      completion(.success(data))
                    }
                }
             } catch {
                 print(error)
                 completion(.failure(.jsonError))
             }
         }
        if let error = error {
            print(error.localizedDescription)
            completion(.failure(.unknownError))
        }
    }.resume()
 }

AudioMedia

struct AudioMedia {
let key: String
let audioURL : URL
let mimeType: String

init?(audioWithURL url: URL, forKey key: String) {
    self.key = key
    self.mimeType = "audio/m4a"
    self.audioURL = url
  }
}

问题是您没有在请求中包含文件名(包括重要的文件类型)。尝试将此字符串紧跟在起始边界之后和音频数据之前:

"Content-Disposition:form-data; name=\"audiofile"; filename=\"audio.m4a\"\r\n\r\n"