我需要上传数据到API。参数:
ios - 如何将数据上传到API?-LMLPHP
我有下一个代码:

static func uploadNewInfo(uploadData: Data) {
        if let url = URL(string: TaskManager.httpString + "sett_eic.htm") {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.httpBody = uploadData
            request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
            let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                if error == nil {
                    print("uploaded")
                }
            }
//            let task = URLSession.shared.uploadTask(with: request, from: uploadData) { (data, response, error) in
//                if error == nil {
//                    print("uploaded")
//                }
//            }
            task.resume()
        }
    }

但反应是"500 Internal Server Error: Expected data not present\r\n"
我不明白怎么才能上传这些数据。我读了一些关于如何上传图片的答案,但不明白。我的数据不是图像。它是字节,用来描述名称、状态等。
更新
这是请求在浏览器中的外观:
ios - 如何将数据上传到API?-LMLPHP
与PRF64分离。。。-上传数据

最佳答案

你可以试试这个:

func uploadNewInfo(uploadData: Data) {
    let boundry = "**********"
    if let url = URL(string: TaskManager.httpString + "sett_eic.htm") {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        //        request.httpBody = uploadData
        request.addValue("multipart/form-data; boundary=\(boundry)", forHTTPHeaderField: "Content-Type")
        var dataForm = Data()
        dataForm.append("\r\n--\(boundry)\r\n".data(using: .utf8)!)
        dataForm.append("Content-Disposition: form-data; name=\"param1\";\r\n\r\n10001".data(using: .utf8)!)
        dataForm.append(uploadData)
        dataForm.append("\r\n--\(boundry)--\r\n".data(using: .utf8)!)
        request.httpBody = dataForm

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error == nil {
                print("uploaded")
            }
        }
        task.resume()
    }
}

如果有效,请告诉我:)

10-07 19:06
查看更多