Swift:通过URLRequest发送图像对象

kg7wmglp  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(150)

我有一个对象的数组,它具有以下值:

var pictures = [Pictures]

struct Pictures: Codable, Hashable {
  var picName1: String
  var picName2: String
  var picName3: String
  var picFile1: UIImage
  var picFile2: UIImage
  var picFile3: UIImage
}

我想通过URLRequest将其发送到我的API。
我遇到了一些HTTP结构问题。
我不断得到回应:"Failed to read the request form. Multipart body length limit 16384 exceeded."
这是我的网络/API调用代码:

func sendPicturesToServer() {
    let url = URL(string: "https://myapicall.com/noodles")
    let body = try! JSONEncoder().encode(pictures)
    let boundary = "---------------------------14737809831466499882746641449"
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = body
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
      guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
      }
      
      do {
        let serializedResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
          print("Serialized Response: \(serializedResponse)")
      } catch {
        print(error)
      }
    }
    task.resume()
  }
}

有人有什么建议吗?

nue99wik

nue99wik1#

func postApiDataWithMultipartForm<T:Decodable>(requestUrl: URL, request: ImageRequest, resultType: T.Type, completionHandler:@escaping(_ result: T)-> Void)
{
    var urlRequest = URLRequest(url: requestUrl)
    let lineBreak = "\r\n"

    urlRequest.httpMethod = "post"
    let boundary = "---------------------------------\(UUID().uuidString)"
    urlRequest.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "content-type")

    var requestData = Data()

    requestData.append("--\(boundary)\r\n" .data(using: .utf8)!)
    requestData.append("content-disposition: form-data; name=\"attachment\" \(lineBreak + lineBreak)" .data(using: .utf8)!)
    requestData.append(request.attachment .data(using: .utf8)!)

    requestData.append("\(lineBreak)--\(boundary)\r\n" .data(using: .utf8)!)
    requestData.append("content-disposition: form-data; name=\"fileName\" \(lineBreak + lineBreak)" .data(using: .utf8)!)
    requestData.append("\(request.fileName + lineBreak)" .data(using: .utf8)!)

    requestData.append("--\(boundary)--\(lineBreak)" .data(using: .utf8)!)

    urlRequest.addValue("\(requestData.count)", forHTTPHeaderField: "content-length")
    urlRequest.httpBody = requestData

   // let multipartStr = String(decoding: requestData, as: UTF8.self) //to view the multipart form string

    URLSession.shared.dataTask(with: urlRequest) { (data, httpUrlResponse, error) in
        if(error == nil && data != nil && data?.count != 0)
        {
        // let dataStr = String(decoding: requestData, as: UTF8.self) //to view the data you receive from the API
            do {
                let response = try JSONDecoder().decode(T.self, from: data!)
                _=completionHandler(response)
            }
            catch let decodingError {
                debugPrint(decodingError)
            }
        }

    }.resume()

}

相关问题