Swift:无法使用 URLSession 上传多张图片

时间:2021-05-08 17:50:36

标签: ios swift postman nsurlsession

我正在尝试通过 MultipartFormData

将多张图片上传到服务器

我阅读了很多链接,但无法解决我的问题。当我们上传 .jpg 或 .png 单个文件时,代码正常工作。

Postman多张图片上传成功。

核心逻辑

let boundaryPrefix = "--\(boundary)\r\n"
body.append("\(boundaryPrefix)".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\"; filename=\"\(listOfFiles[0].name)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
body.append(convertFileToData(url: listOfFiles[0].pathURL)!)
body.append("\r\n".data(using: .utf8)!)
    
body.append("\(boundaryPrefix)".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\"; filename=\"\(listOfFiles[1].name)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/jpg\r\n\r\n".data(using: .utf8)!)
body.append(convertFileToData(url: listOfFiles[1].pathURL)!)
body.append("\r\n".data(using: .utf8)!)
    
body.append("--".appending(boundary.appending("--")).data(using: .utf8)!)


func convertFileToData(url: URL) -> Data? {
    do {
        let fileData = try Data(contentsOf: url)
        return fileData
    } catch {
        return nil
    }
}


session.dataTask(with: urlRequest) { (dataa, response, error) in
     if error == nil {
         if let _ = dataa {
              do {
                  let val = try JSONDecoder().decode(UploadResponse.self, from: dataa!)
              } catch {
              }
         } else {  }
     } else { }
 }.resume()

问题:

  • 只有第一个 Image 数组到达服务器。
  • 第二张图片没有到达服务器。

我犯了什么错误?

1 个答案:

答案 0 :(得分:0)

试试这个:

let boundary = "Boundary-\(UUID().uuidString)"
let boundarySuffix = "--\(boundary)--\r\n"
                
    if let images = files,images.count > 0 {
             let boundaryPrefix = "--\(boundary)\r\n"
             request?.addValue("multipart/form-data; boundary=" + boundary, forHTTPHeaderField: "Content-Type")
             let data = NSMutableData()
             if let params = parameters,params.count > 0{
                for (key, value) in params {
                    data.append("--\(boundary)\r\n".nsdata)
                    data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".nsdata)
                    data.append("\((value as AnyObject).description ?? "")\r\n".nsdata)
                 }
              }
              for file in images {
                  data.append(boundaryPrefix.nsdata)
                  data.append("Content-Disposition: form-data; name=\"\(file.name!)\"; filename=\"\(NSString(string: file.filename!))\"\r\n\r\n".nsdata)
                   if let a = file.data {
                      data.append(a)
                      data.append("\r\n".nsdata)
                   } else {
                      print("Could not read file data")
                   }
               }
               data.append(boundarySuffix.nsdata)
               request?.httpBody = data as Data
    }