Three points have been raised about this text:
- it's not a complete sentence
- the word order seems unusual
- there appears to be two nouns but no prepositions.
The fact that it's not a complete sentence is irrelevant: this is normal for titles of films and books. There are many examples of complete sentences that use the same construction, and the OP has added now added two of them to his question.
The film is from an autobiographical book, so I think we can reasonably analyse the title as if it were a predicate complement of I was.
I was twelve years a slave.
It seems to me that a slave would also make sense as a predicate complement on its own:
I was a slave.
so the unusual part is not "a slave" but "twelve years".
Regarding the word order, some people have pointed out the similarity to sentences like "twice a winner", rather than "a winner twice". Note that twice is an adverb, and adverb positioning can be flexible. Yes, there are 'rules', but these rules are really guidelines, and they change over time and with regional dialects.
The final point is about the absence of prepositions. There are many examples of sentences that concern time periods and do not have prepositions, some of which show this inversion. As the book was published in 1853, I have picked some examples from the 19th century, though it is possible to find examples back to the 16th century that show the absence of preposition and the inversion.
When I met Wolseley first, in 1877, he had been but twenty-one years a soldier
[He was] two weeks an invalid (1882)
He was out of the prison about ten months (1881)
[She is] now a widow, and in the house nearly five years with her oldest child (1882)
I am wondering whether these time intervals are treated as adverbs of time duration, like long. This would explain the absence of preposition and also the flexibility in positioning:
She did not long remain a widow (1824)
[I] began to think I should not be a soldier long (1853)