MultipartForm Request: How to make the distinction between replace or delete file on server

16 Views Asked by At

How can I make a distinction between replacing vs deleting a file on my server by a PUT request?

Lets say I have an endpoint for updating my user. A user can have a picture and a backgroundPicture. It also has simple fields like age or username.

The following could the user be requesting:

  1. Update all fields (picture and backgroundPicture are set and getting replaced)
  2. User only wants to update age (picture and backgroundPicture are set to null)
  3. User wants to replace backgroundPicture but delete picture (picture is set to null)

How can my endpoint know if in (2.) the picture and backgroundPicture fields should be ignored instead of delete it? Similar question goes for (3.): How can it know that the existing picture should be deleted.

Solutions which I thought about

  • Add additional boolean flag param like deletePicture and deleteBackgroundPicture
    • Cons: Additional fields and feels misused
  • Make a separate put/delete endpoint for files (e.g. [DELETE] /users/{id}/picture)
    • Cons: Updates are not atomic anymore and client requires two requests instead of one.

What is the best practice in these situations? I am sure, that I am not the first one with this issue :)


For those who can't imagine it programmatically:

data class UserDTO(
  val id: UUID,
  val username: String, 
  val age: Int, 
  @FormParam(FormParamKey.PICTURE) @PartType(MimeType.IMAGE_JPEG) val picture: File?,
  @FormParam(FormParamKey.BACKGROUND_PICTURE) @PartType(MimeType.IMAGE_JPEG) val backgroundPicture: File?
)

Lets say my endpoint looks like this

@PUT
@Path("/users/{id}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
suspend fun putMultiPart(
    @RestPath id: UUID,
    userDTO: UserMultipartDTO,
    @Context httpRequest: HttpServerRequest
): Response { ... }
0

There are 0 best solutions below