【问题标题】:Add a custom custom parameter to Multipart upload向分段上传添加自定义自定义参数
【发布时间】:2021-09-01 05:21:54
【问题描述】:

我正在尝试将图像发送到服务器,但它不断向我抛出 400 错误。我的猜测是它在体内。但是邮递员的请求会成功。

邮递员请求

我的代码如下

  /*****Multipart Upload*********/
  func uploadImage(paramName: String, fileType: String, image: UIImage,id:String,comepletion:@escaping ()->Void,failure:@escaping (String)->Void) {

    let url = URL(string: "https:someURL")

    let boundary = UUID().uuidString

    let session = URLSession.shared

    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "POST"

    urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    urlRequest.setValue(id, forHTTPHeaderField: "some_id")
   

    // Add the image data to the raw http request data
    data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
  
      //I guess the issue is in the bellow line since I'm 
     // supposed to send a param called "files" as per the postman screenshot

    data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileType)\"\r\n".data(using: .utf8)!)//Issue is here 
    data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
    data.append(image.pngData()!)

    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)
            }
           // comepletion()
        }else {
            failure(error?.localizedDescription ?? "")
        }
    }).resume()
}

【问题讨论】:

    标签: swift multipartform-data swift5


    【解决方案1】:

    看来你把Content LengthurlRequest 弄丢了

    尝试添加:

    urlRequest.setValue(String(data.count), forHTTPHeaderField: "Content-Length")

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 2023-04-10
      • 2022-01-25
      • 2020-09-24
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      相关资源
      最近更新 更多