ios - 使用 Swift 3 将图像转换为 Base64 时出现问题

标签 ios swift api imgur

我正在尝试将图像上传到 imgur 并希望获得图像的 url。 Imgur 要求传入的图像是二进制文件、base64 数据或图像的 URL。我正在将图像转换为 Base64,但收到一条错误消息,指出它是无效的文件类型。

这是我的代码:

  let imageData = UIImagePNGRepresentation(checkView.image!)
    let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)

    let urlPath = "https://api.imgur.com/3/upload"
    let url = URL(string:urlPath)

    var request = URLRequest(url: url!)
    request.setValue("Client-ID MyClientIDKEy", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"

    // create post string with username and password
    let postString = "image=" + base64Image!
    request.httpBody = postString.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            // check for fundamental networking error
            print("Data empty or error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 405 {
            // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response from status code = \(String(describing: response))")
        }

        // store data
        let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
        let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

        // printing feedback
        print("responseString = \(responseString)")
        print("--------------------------------")
        print(json)
        print("--------------------------------")

    }
    task.resume()
}

以及我得到的回复:

statusCode should be 200, but is 415
response from status code = Optional(<NSHTTPURLResponse: 0x1c0225280> { URL: https://api.imgur.com/3/upload } { Status Code: 415, Headers {
"Access-Control-Allow-Origin" =     (
    "*"
);
"Cache-Control" =     (
    "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
);
"Content-Length" =     (
    174
);
"Content-Type" =     (
    "application/json"
);
Date =     (
    "Sat, 18 Nov 2017 23:14:27 GMT"
);
Server =     (
    nginx
);
"access-control-allow-headers" =     (
    "Authorization, Content-Type, Accept, X-Mashape-Authorization, IMGURPLATFORM, IMGURUIDJAFO, SESSIONCOUNT, IMGURMWBETA, IMGURMWBETAOPTIN"
);
"access-control-allow-methods" =     (
    "GET, PUT, POST, DELETE, OPTIONS"
);
"access-control-expose-headers" =     (
    "X-RateLimit-ClientLimit, X-RateLimit-ClientRemaining, X-RateLimit-UserLimit, X-RateLimit-UserRemaining, X-RateLimit-UserReset"
);
"x-post-rate-limit-limit" =     (
    1250
);
"x-post-rate-limit-remaining" =     (
    1246
);
"x-post-rate-limit-reset" =     (
    3039
);
} })

 responseString = Optional({"data":{"error":{"code":1003,"message":"File type invalid (2)","type":"ImgurException","exception":{}},"request":"\/3\/upload","method":"POST"},"success":false,"status":415})

Optional(["status": 415, "data": {
    error =     {
        code = 1003;
        exception =         {
        };
        message = "File type invalid (2)";
        type = ImgurException;
    };
    method = POST;
    request = "/3/upload";
}, "success": 0])

--------------------------------
nil
--------------------------------

最佳答案

如果您希望 JSON 返回为 application/json,请确保您的 header 包含 Content-TypeAccept:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

关于ios - 使用 Swift 3 将图像转换为 Base64 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47372363/

相关文章:

c - 调用 Lua API 时出现不 protected 错误(尝试调用空值)

java - 当代码位于 try 和 catch 语句中时,为什么会引发 StackOverflowError?

ios - 分段控制切换多个表格 View

ios - 在带有 Core Data 的 IOS 应用程序中,我应该将业务逻辑放在哪里?

swift - 如何在 swift 中向字典添加新键?

ios - 两次之间的分钟数

ios - 无法验证您的应用程序错误

c# - 在 Unity Android 和 iOS 部署中从收件箱读取短信

ios - 尝试使用 swift 将 XML 从 URL 解析为 PickerView

java - 无法下载 javax.comm