简体   繁体   中英

sending Image as POST in SWIFT

I am trying to post an UIImage to a API to read the text from that UIImage but getting the following error: Also, How do I print urlRequest on console to see what are the elements in it. I have tried Alamofire also, but the issue seems to be in request which is not sent properly. Any type of help is much appreciated.

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";
        };
    }

MY CODE IS:

`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()
    }`    

You are putting Data from an image file and Data for the form body together.

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
        ...
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM