It is fair to say that companies, at first glance, prefer to sponsor a winning team instead of a midfield team. However, several considerations need to be made before saying that this is always the right thing to do.
Reputation: being the partner of a team that every Sunday fights for wins clearly helps to strengthen your company's reputation, particularly if you are a technology partner of that team, providing them with the solutions to perform better on track. Differently, if you are a more standard partner (like a bank or an entertainment company) this aspect is not crucial. And sometimes, an unexpected podium or win from a midfield team can be a very powerful marketing story to tell as a sponsor.
Visibility: some may think that a winning team gets much more TV coverage than a midfield team and this is not true. Formula 1, for example, constantly tries to distribute TV coverage equally. Moreover, because drivers in the midfield tend to battle more than the ones in the first positions, they generally get more TV coverage than the front-runners. In fact, in the past, dominant teams have even complained of a lack of TV coverage.
Support: the top teams tend to have bigger marketing departments but also a larger number of sponsors to serve, therefore flexibility and availability to activate the sponsorship can be affected by how the workload is managed inside the team. However, when it comes to utilising the drivers or some particular team asset (like the factory) for promotional purposes you might need a lot of planning as the number of requests also from other sponsors is high. Differently, activating a sponsorship with a smaller team can be easier, although the sponsor might need to do a bit more work internally as the team resources are limited.
Investment: a partnership with a championship-winning team will be massively more expensive than with a midfield team, so if you have the proper budget to still have a comprehensive marketing rights package it is the right thing to do. But, if you have to reduce to the minimum your partnership benefits to be with a top team, then is better to be with a midfield team having more assets to deploy.
Conclusively, there is no right or wrong, it really depends on the objectives and budget of the sponsor. A well-structured and carefully planned sponsorship always works, but in order to do that, you need expert, competent and independent guidance.