How to parse request.body for multipart file in django

I have used below code to post data to url

public void updateLogo(String clientKey, MultipartFile file) {
    MultipartBodyBuilder builder = new MultipartBodyBuilder();
    builder.part("file", file.getResource());

    Settings prevData = repo.findFirstByClientKey(clientKey);
    WebClient webClient = WebClient.builder().baseUrl("http://localhost/")
            .defaultHeader(HttpHeaders.AUTHORIZATION, String.format("Token %s", userToken)).build();
        Mono<SettingsLogo> resObj = webClient.post().uri("api/upload-logo")
                .contentType(MediaType.MULTIPART_FORM_DATA).body(BodyInserters.fromMultipartData(builder.build()))
                .retrieve().bodyToMono(SettingsLogo.class)
                .onErrorResume(WebClientResponseException.class, ex -> {
                    logger.error("Exception", ex);
                    return Mono.empty();
                });
}

On Django post function

class UpdateJiraAppLogo(APIView):

def post(self, request, *args, **kwargs):
    print('POST', request.POST)
    print('BODY', request.body)
    print('FILES', request.FILES)
    logo = request.body
    now = timezone.now()
    logo_name = "logo_" + str(now.strftime('%d_%m_%Y') + "_" + now.strftime('%H%M%S')) + ".png"

    try:
        with open("media/logos/" + logo_name, "wb+") as f:
            f.write(logo)
            f.close()
    except Exception as e:
        print(e)

Following is printed

POST <QueryDict: {}>

BODY b'--3oqd3VUazPhxbazUKCTiNsp2MeoS9RgQqbQLnj7X\r\nContent-Disposition: form-data; name="file"; filename="clock.png"\r\nContent-Type: image/png\r\nContent-Length: 1959\r\n\r\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00x\x00\x00\x00x\x08\x03\x00\x00\x00\x0e\xba\xc6\xe0\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00u0\x00\x00\xea`\x00\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x01\xefPLTE\x00\x00\x00\xe399\xde11\xde33\xdc33\xdd44\xdd33\xdd33\xdd33\xdd33\xdd33\xde44\xdf@@\xff\x00\x00\xdb55\xdc33\xdd33\xdd33\xdd33\xdd44\xde44\xdb11\xde77\xdc22\xde44\xdd33\xdd22\xde22\xdc..\xdb$$\xde22\xdd33\xdd33\xdd33\xdd22\xdc44\xe633\xdf33\xdc33\xdd33\xde44\xdd55\xdd33\xdd33\xdd33\xdd55\xdc33\xde33\xdc44\xdd33\xdb11\xe399\xde33\xdd33\xdc22\xdb11\xdd33\xdd33\xff\x00\x00\xde11\xdd22\xdd33\xdd33\xdd33\xdd33\xde44\xbf@@\xdd44\xd5++\xdc55\xdd33\xdb77\xe022\xdd33\xdc33\xdd33\xde44\xdd33\xdd44\xdd33\xdd33\xdc44\xdd33\xdd33\xdd33\xde33\xdd33\xcc33\\x00\x00\x00%tEXtdate:create\x002019-06-02T16:58:33+00:00.c\xfc\x1c\x00\x00\x00%tEXtdate:modify\x002019-06-02T16:58:33+00:00_>D\xa0\x00\x00\x00\x00IEND\xaeB`\x82\r\n--3oqd3VUazPhxbazUKCTiNsp2MeoS9RgQqbQLnj7X--\r\n'

FILES <MultiValueDict: {}>

the file is saved but it is corrupted. How to save file when file is received in request.body rather than FILES or POST?

Back to Top