PHP将64位数据解码为jpeg,以便在Web浏览器中查看

时间:2016-06-22 06:01:24

标签: php ios swift post

从我的iOS应用程序中,我使用base64编码的jpg图像创建一个POST请求,如此

    let imageData = UIImageJPEGRepresentation(image, 1.0)

    if(imageData == nil ) { return }

    let request = NSMutableURLRequest(URL: NSURL(string:"\(self.ip)")!)
    request.HTTPMethod = "POST"
    request.setValue("Keep-Alive", forHTTPHeaderField: "Connection")


    let base64Encoded = imageData!.base64EncodedDataWithOptions(.Encoding64CharacterLineLength)
    let postString = "id=\(self.user.userID)&image=\(base64Encoded)"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

    let task = session.dataTaskWithRequest(request) { ...

然后,在我的PHP文件中我有

$imgData = base64_decode($_POST["image"]);

if(file_put_contents('image.jpg', $imgData)) {
  echo json_encode([
    "message" => "The file has been uploaded.",
    "status" => "success",
    "id" => $id
  ]);
}
else {
  echo json_encode([
    "message" => "The file has failed uploading.",
    "status" => "error",
    "id" => $id
  ]);
}

PHP文件说它已全部正确上传,但当我转到image.jpg的网址时,它没有显示图片,只是一个问号。

图像真的存在吗?我可以看到image.jpg的文件大小在变化,但我无法查看图像。谢谢!

1 个答案:

答案 0 :(得分:1)

var base64Encoded = imageData!.base64EncodedStringWithOptions([])
base64Encoded = base64Encoded.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-._~"))!