I think it's okay but it's somewhat awkward because the phrase "having read the book" is intended to modify "I" which is too far away in the sentence. The reader is therefore inclined to think that "having read the book" modifies "ending" or "story" which doesn't make sense. Punctuation helps but it's still awkward. It's better to keep adjectives and adjective phrases as close as possible to the words they modify.
Having read the book, I already knew the ending.
I, having read the book, already knew the ending.