Japan staged a heroic comeback against Spain to win 2-1 and book their place in the round of 16 at the World Cup.