Upload and files using Rest API

Asked

Viewed 1,994 times

1

I am creating an end-point to upload a file in the format (.txt) but my entity does not consist only of the file. There are other attributes, so I need to send a 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 am using springBoot to work controllers. The file type is Multipart.

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

  • It is not possible to send a file through JSON, except if you convert it to Base64, for example.

  • even if I change the enctype attribute of the form tag to: enctype="Multipart/form-data"

1 answer

1

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

The downside of this method is the effort to convert the file to Base64 on the client and then convert to text again 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 a few KB and over which I had full control of the request in the client.

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

If you want a more elaborate solution that meets any type and file size, I suggest you make the client submit two requests. In the first, you send only the attributes. The entity is created and returns the URL for uploading 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.

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 jam the original application server.

  • Thanks for the tip, I figured you’d go that way anyway. I will drive initially doing with Base64 because I’m sure my file is small, however my format is not txt is binary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.