【问题标题】:How to send the image file with value as image, key as 'file'如何发送值为图像的图像文件,键为“文件”
【发布时间】:2019-09-24 17:33:15
【问题描述】:

由于我是iOS新手,在这里停留了一段时间,我需要将图像上传到具有键和值的服务器(“文件”:图像),在邮递员中找到附加的图像。

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

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

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] 传递给正文。

提前致谢

【问题讨论】:

标签: ios swift nsurlrequest


【解决方案1】:

您可以使用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)
            }
         }
     }
    

【讨论】:

  • 另外,对于大文件,您可以考虑使用请求正文流并一次提供数据块。图像可能一次就可以很好地编码,但是如果您需要上传视频,那就是您的做法。
  • param 是什么?随处可见,但在我们的案例中不需要...
  • 应根据您的需要定制
【解决方案2】:

试试这个。将文件保存在documentDirectory 中。使用boundary 在正文中添加文件,这是一个随机字符串。然后添加文件的key为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)!)

}

【讨论】:

  • 我已经在名为(IMG_1302.JPG) 的项目中复制了图像,在您的指导下,我复制了如下代码............ body.append("-- (边界)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition: form-data; name=\"file\"; filename=\"IMG_1302.JPG\ "\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Type: image/*\r\n\r\n".data(using: String.Encoding.utf8 )!) body.append("\r\n".data(使用: String.Encoding.utf8)!) body.append("--(boundary)--\r\n".data(使用: String. Encoding.utf8)!).. 但仍然无法得到响应
  • 如果您遇到任何错误,请发布。否则我认为如果你做错了什么,你应该和你的后端开发人员一起调试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 2019-03-22
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多