A crucial late try by South Africa captain Fourie Du Preez secured a dramatic victory for the Springboks after a heroic defensive performance by Wales.