This article is related to a former article in which I claimed that "there is no support to directly upload images using REST in Drupal 8". Since Drupal 8.6 this in no longer true (https://www.drupal.org/node/1927648). You can read how to use this new functionality at https://wimleers.com/blog/api-first-drupal-file-uploads and https://wimleers.com/blog/api-first-drupal-8.6.
This article is, however, about an entirely different method to upload a file in Drupal 8 for the somewhat unusual use case of passing the uploaded file to a third party REST api. Not that the method described here will be limited to that use case, but in most cases the new Drupal 8.6 functionality will be the preferred choice.
The situation was that for a decoupled set-up the front-end needed to upload a file to a third party REST api. For that upload the third party needed info about the user present in Drupal that the front-end was not allowed to retrieve or expose in any way. Also, as a temporary solution Drupal needed to perform a virusscan on the uploaded files. The front-end strongly preferred the use of a multipart/form-data content type for the POST request.
So, the uploaded file is not meant for storing in the Drupal application and not meant to be saved as File object. The method shown below does do that anyway, because the clamav module, used for the virus scan, requires it.
As usual I start with a new module:
# my_api.info.yml name: My REST Service type: module description: "REST Service for passing file upload" package: Web services core: '8.x'
And since I need to create the end-point for this REST api myself, I create the route for this end-point: