ios - 在 SWIFT 中将图像作为 POST 发送

标签 ios swift image post

我正在尝试将 UIImage 发布到 API 以从该 UIImage 读取文本,但出现以下错误: 另外,如何在控制台上打印 urlRequest 以查看其中的元素。我也尝试过 Alamofire,但问题似乎是请求未正确发送。非常感谢任何类型的帮助。

Error: 
    AsSynchronous{
        error =     {
            code = 400;
            message = "Wrong request: No file sent in the request, please set the field 'files'";
            requestId = "d9adb89b-cd67-48e4-7846-0aa4c78fc08e";
        };
    }

我的代码是:

`func uploadImage(paramName: String, fileName: String, image: UIImage,apiKey:String) {

        let boundary = UUID().uuidString


        let urlRequest = NSMutableURLRequest(url: NSURL(string: "https://xxxxxxxxxxxxx")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        urlRequest.httpMethod = "POST"


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

        let headers = [
            "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
            "apikey": "yyyyyyyyyyyyyyyyy",
            "cache-control": "no-cache",
            "Postman-Token": "87b45036-1107-4db6-bf4d-7dc83314045b"
        ]
        urlRequest.allHTTPHeaderFields = headers
        var data = Data()
        var value = "files"
        // Add the userhash field and its value to the raw http reqyest data
        data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
        data.append("Content-Disposition: form-data; name=\"\(paramName)\"\r\n\r\n".data(using: .utf8)!)
        data.append("\(value)".data(using: .utf8)!)

        // Add the image data to the raw http request data
        data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
        data.append("Content-Disposition: form-data; name=\"image\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
        data.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
        data.append(UIImageJPEGRepresentation(image, 0.1)!)


        data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

        urlRequest.httpBody = data


        print("value of data is", data)

        //NSString requestReply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        //print("requestReply: %@%@", requestReply);

        let session = URLSession.shared
        let dataTask = session.dataTask(with: urlRequest as URLRequest, completionHandler: { (data, response, error) -> Void in
            if let _data = data
            {
                do {
                    var jsonResult: NSDictionary
                    try jsonResult = JSONSerialization.jsonObject(with: _data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                    print("AsSynchronous\(jsonResult)")
                }
                catch {
                    // handle error
                }
            }
            else
            {
                print("Error: no data for request \(urlRequest)")
            }
            /* if (error != nil) {
                print(error)
            } else {
                let httpResponse = response as? HTTPURLResponse
                print("got any response")
                print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue))
                print("may be")

                print(httpResponse)

            }*/
        })

        dataTask.resume()
    }`    

最佳答案

您将图像文件中的 Data 和表单主体的 Data 放在一起。

class HomeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func postTapped(_ sender: UIButton) {
        postData()
    }

    func postData() {
        let image = UIImage(imageLiteralResourceName: "myImage.jpg")
        guard let imageData = UIImageJPEGRepresentation(image) else {
            print("oops")
            return
        }
        let url = URL(string: "http://www.example.net/example.php")
        var request = URLRequest(url: url!)
        request.httpMethod = "POST"
        request.timeoutInterval = 30.0

        let uuid = UUID().uuidString
        let CRLF = "\r\n"
        let filename = uuid + ".jpg"
        let formName = "file"
        let type = "image/jpeg"     // file type
        let boundary = String(format: "----iOSURLSessionBoundary.%08x%08x", arc4random(), arc4random())
        var body = Data()

        // file data //
        body.append(("--\(boundary)" + CRLF).data(using: .utf8)!)
        body.append("Content-Disposition: form-data; name=\"formName\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
        body.append(("Content-Type: \(type)" + CRLF + CRLF).data(using: .utf8)!)
        body.append(imageData as Data)
        body.append(CRLF.data(using: .utf8)!)

        // footer //
        body.append(("--\(boundary)--" + CRLF).data(using: .utf8)!)
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        request.httpBody = body
        let session = URLSession(configuration: .default)
        session.dataTask(with: request) { (data, response, error) in
        ...
        ...
    }
}

关于ios - 在 SWIFT 中将图像作为 POST 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013763/

相关文章:

ios - 如何获取 emailAddress 以发现 UserIdentity?

javascript - 加载图像时显示处理 JQuery/Javascript

jquery - Feed 图像显示在某些浏览器中旋转

ios - TableView 在查询后未填充 (PFQuery)

swift - 对实体数组执行 `map` 时获取 nil 值

ios - 从图库中获取图像很慢

ios - 自定义 UIButton 子类

ios - 在 MapKit 中的多边形中心添加标签

iphone - 在 ViewController 中启用编辑模式

ios - 响应 child 和 parent 的触摸事件