Ios 在SWIFT中以邮寄方式发送图像

Ios 在SWIFT中以邮寄方式发送图像,ios,swift,image,post,Ios,Swift,Image,Post,我试图将UIImage发布到API以从该UIImage读取文本,但出现以下错误: 另外,如何在控制台上打印urlRequest以查看其中的元素。我也试过Alamofire,但问题似乎在请求中,没有正确发送。非常感谢任何类型的帮助 Error: AsSynchronous{ error = { code = 400; message = "Wrong request: No file sent in the requ

我试图将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()
    }`    

您正在将图像文件中的
数据
和表单主体的
数据
放在一起

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

再次面对同样的问题。使用您的代码唯一的区别是我添加了与ImageView.image相同的let image=ImageView.imageIS UIImage(imageLiteralResourceName:“myImage.jpg”)?我必须先将UIImage保存为'myIn=mage.jpg'吗?如果是,我该怎么做?