Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

php - Laravel - using a postgre bytea blob field

I am using PostgreSQL on a Laravel installation. A table has a bytea type field which is being used to store binary data (base64_encoded file contents).

When I use Eloquent to retrieve the table I get a resource type variable being returned in this field.

How can I rather retrieve this as a string?

$raw = Media::where('id','=',$id)->first();
$raw->file_data = base64_decode($raw->file_data);   // doesn't work
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the author of this question did not post the details to the answer, I will post my findings here.

As the returned field is a handle to a stream you can use the stream_get_contents function to read the value into a string, you can then use pg_unescape_bytea to get the actual value of the bytea data. Finally use the htmlspecialchars function if you wish to display the bytea data in HTML.

Example code:

$my_bytea = stream_get_contents($resource);
$my_string = pg_unescape_bytea($my_bytea);
$html_data = htmlspecialchars($my_string);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...