在SWIFT中以POST方式发送图片

时间:2019-03-06 00:37:38

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

1 个答案:

答案 0 :(得分:0)

您要将图像文件中的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
        ...
        ...
    }
}