Swift - 将二进制文件发送到服务器(转换为字符串请求)

Swift - Sending binary file to a server (convert to string request)

这是我构建发送到服务器的请求的函数。当它是一个小的纯文本文件时,这段代码工作得很好。但是,当我向它传递一个二进制文件时,它会在下面指示的行上崩溃(当它试图将其转换为 utf 字符串并爆炸 b/c 时,转换不起作用,因为它创建了一个 nil 值):

func buildFilePushRequest(fromUrl url: URL, httpBody: Data? = nil, fileName: String) -> NSMutableURLRequest? {
    let cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
    let request = NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: 2.0)
    request.httpMethod = "POST"

    // Set Content-Type in HTTP header.
    let boundaryConstant = "Boundary-7MA4YWxkTLLu0UIW"; // This should be auto-generated.
    let contentType = "multipart/form-data; boundary=" + boundaryConstant

    let fileName = fileName

    request.setValue(contentType, forHTTPHeaderField: "Content-Type")
    request.setValue("keep-alive", forHTTPHeaderField: "Connection")

    var dataString = "--\(boundaryConstant)\r\n"
    dataString += "Content-Disposition: form-data; name=file; filename=\"\(fileName)\"\r\n"
    dataString += "Content-Type: octet-stream\r\n\r\n"
    dataString += String(data: httpBody!, encoding: .utf8)! <-- CRASHES HERE
    dataString += "\r\n"
    dataString += "--\(boundaryConstant)--\r\n"

    print("dataString: \(dataString)")

    let requestBodyData = dataString.data(using: .utf8)
    request.httpBody = requestBodyData

    return request
}

我读到一点,对于二进制类型数据,base64 比 utf8 更好,但我不确定如何最好地修改上面的代码来使用它,或者如果有更好的解决方案?提前致谢!

如果 httpBody 参数可以包含二进制数据,您可以将整个 http 正文复合为 Data

首先请使用原生 URLRequest,它是可变的 variable 为什么 return 值是可选的?

func buildFilePushRequest(fromUrl url: URL, httpBody: Data? = nil, fileName: String) -> URLRequest {
    var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 2.0)

...

var data = Data("--\(boundaryConstant)\r\n".utf8)
data += Data("Content-Disposition: form-data; name=file; filename=\"\(fileName)\"\r\n".utf8)
data += Data("Content-Type: octet-stream\r\n\r\n".utf8)
if let body = httpBody { data += body }
data += Data("\r\n".utf8)
data += Data("--\(boundaryConstant)--\r\n".utf8)

request.httpBody = data