Upload and files using API Rest

1

I'm creating an end-point to output a file in the format (.txt), but my entity is not just the file. There are other attributes, so I need to send json this way to the server:

{
"nomeCliente" : "teste", 
"arquivo": // aqui eu enviaria o arquivo.
}

But this way the file does not reach the server. I'm using springBoot to work controllers. The file type is Multipart.

My question is, how can I do this? or you should send the file first and then the rest of the data.

    
asked by anonymous 20.03.2018 / 18:12

1 answer

1

If the file is small (a few KB) and is always a plain text file (.txt) you can convert the contents to Base64 and send in the payload of the JSON object.

The down side of this method is the effort to convert the file to Base64 on the client and then convert to text back on the server. In addition, the resulting Base64 string would be about 1/3 larger than the original file. For this reason, I would only use this method for files of some KB and over which I had full control of the request on the client .

If you do not have control of what is being sent, a malicious client could send a request with a multiple64 Base64-encoded file and cause problems to your server.

If you want a more elaborate solution that fits any type and size of file, I suggest you have the client send two requests. At first, you only submit the attributes. The entity is created and returns the URL to send the image.

Example of the first request:

PUT /restapi/v1/clientes HTTP/1.1
Host: www.seuhost.com.br/

{
  "nomeCliente" : "Jean", 
  //Outros atributos 
}

Return with status 201 (created):

{
  meta: {
  },
  data: {
    "urlArquivo": "http://www.seuhost2.com.br/apirest/v1/clientes/id/123456/arquivo"
  }
}

The client would then use this URL to send the file.

In this way, you can create specific controls on the uploaded file. You can even determine that all files are sent to another server, so as not to overload the original application server.

    
20.03.2018 / 21:35