如何发送值为image,key为'file'的图片文件

How to send the image file with value as image, key as 'file'

由于我是 iOS 的新手,我在这里停留了一段时间,我需要将图像上传到服务器,键和值为 ("file": image),找到图像如邮递员所附。

这里的几乎所有建议我都试过了How to upload images to a server in iOS with Swift?,

这里我尝试了一些但没有得到输出响应,因为请求中没有传递密钥

let url = URL(string: uploadurl);
let request = NSMutableURLRequest(url: url!);
request.httpMethod = "POST"
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 1)
if (imageData == nil) {
    print("UIImageJPEGRepresentation return nil")
    return
}
let body = NSMutableData()
//here I need to pass the data as ["file":image]
body.append(imageData!)
request.httpBody = body as Data
let task =  URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if let data = data {
        // do
        let json =  try!JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
        print("json value \(json)")
    } else if let error = error {
        print(error.localizedDescription)
    }
})
task.resume()

请建议我,如何将这些图像作为 ["file": image] 传递给正文。

提前致谢

您可以使用 URLSession 上传 multipart/form-data

  1. 正在上传

上传图片的功能

    // build request URL

    guard let requestURL = URL(string: "YOURURL") else {
        return
    }

    // prepare request
    var request = URLRequest(url: requestURL)
    request.allHTTPHeaderFields = header
    request.httpMethod = MethodHttp.post.rawValue

    let boundary = generateBoundaryString()

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    // built data from img
    if let imageData = image.jpegData(compressionQuality: 1) {
        request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
    }

    let task =  URLSession.shared.dataTask(with: request,
                                           completionHandler: { (data, _, error) -> Void in

                                            if let data = data {

                                                debugPrint("image uploaded successfully \(data)")

                                            } else if let error = error {
                                                debugPrint(error.localizedDescription)
                                            }
    })
    task.resume()
  1. 正文

将创建请求正文的函数

 func createBodyWithParameters(parameters: [String: String],

                                          filePathKey: String,
                                          imageDataKey: Data,
                                          boundary: String) -> Data {

                let body = NSMutableData()
                let mimetype = "image/*"

                body.append("--\(boundary)\r\n".data(using: .utf8) ?? Data())
                body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filePathKey)\"\r\n".data(using: .utf8) ?? Data())
                body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: .utf8) ?? Data())
                body.append(imageDataKey)
                body.append("\r\n".data(using: .utf8) ?? Data())

                body.append("--\(boundary)--\r\n".data(using: .utf8) ?? Data())



          return body as Data
        }

        private func generateBoundaryString() -> String {
            return "Boundary-\(Int.random(in: 1000 ... 9999))"
        }

    }
  1. 数据扩展

    extension NSMutableData {
    
    func appendString(_ string: String) {
           if let data = string.data(using: String.Encoding.utf8, 
              allowLossyConversion: true) {
                 append(data)
            }
         }
     }
    

试试这个。将文件保存在 documentDirectory 中。使用随机字符串 boundary 在正文中添加文件。然后将文件的密钥添加为 name=\"file\"

if !fileName.isEmpty {
    let pathComponents = [NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!, fileName]
    outputFileURL = NSURL.fileURL(withPathComponents: pathComponents) //get the image file from documentDirectory

    //add file to body (name=\"file\")
    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpeg\"\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Type: image/*\r\n\r\n".data(using: String.Encoding.utf8)!)
    do {
        try body.append(Data(contentsOf: outputFileURL!))
    } catch {
        print(error)
    }
    body.append("\r\n".data(using: String.Encoding.utf8)!)
    body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

}