首页 > 解决方案 > 向分段上传添加自定义自定义参数

问题描述

我试图将图像发送到服务器,但它不断向我抛出 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()
}

标签: swiftmultipartform-dataswift5

解决方案


看来你迷路Content LengthurlRequest

尝试添加:

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


推荐阅读