繁体   English   中英

通过 HTTP 发送文件 Swift 中的发布请求

[英]Send File Over HTTP Post Request in Swift

我对 Swift 真的很陌生,并试图从 iOS 将一些文件上传到树莓派。 我发现 HTTP 发布请求,但我也不太了解。 我实际上是一个嵌入式 linux 程序员。 所以,我像这样发布我的请求

    var data = Data()    
    data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
    data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
    data.append("Content-Type: \"content-type header\"\r\n\r\n".data(using: .utf8)!)
    data.append(read().data(using: .utf8)!)
    data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

显然,如果文件是 txt,我工作得很好,而且我无论如何都找不到读取并将我的原始数据放入这种数据格式。 有什么帮助吗?

读取()->字符串

我无法解释我做了什么,但我试图写清楚

func getFile(fileName: String) -> [UInt8]? {
    // See if the file exists.
    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileURL = dir.appendingPathComponent(fileName)
        do {
            // Get the raw data from the file.
            let rawData: Data = try Data(contentsOf: fileURL)
            // Return the raw data as an array of bytes.
            return [UInt8](rawData)
        } catch {
            // Couldn't read the file.
            return nil
        }
    }
    print("\(fileName) not exist")
    return nil
}
func uploadFile(fileName: String, fileExtension: String, endpoint: String) {
    let fileNameWithExtension = fileName + "." + fileExtension
    let url = URL(string: endpoint)

    var data = Data()
    
    // generate boundary string using a unique per-app string
    let boundary = UUID().uuidString

    let session = URLSession.shared

    // Set the URLRequest to POST and to the specified URL
    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "POST"

    // Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser
    // And the boundary is also set here
    urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    // Add the file data to the raw http request data
//    data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
//    data.append("Content-Disposition: form-data; name=\"name\"; username=\"kemal\"\r\n".data(using: .utf8)!)
    data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
    data.append("Content-Disposition: form-data; name=\"file\"; filename=\"recieved\(fileExtension)\"\r\n".data(using: .utf8)!)
    data.append("Content-Type: \"content-type header\"\r\n\r\n".data(using: .utf8)!)

    print("opening file...")
    if let bytes: [UInt8] = getFile(fileName: fileNameWithExtension) {
        for byte in bytes {
            data.append(byte)
        }
    

    data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
    // Send a POST request to the URL, with the data we created earlier
    session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
        if error == nil {
            let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
            if let json = jsonData as? [String: Any] {
                print(json)
            }
        }
    }).resume()
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM