0

Shall I remove this from application.properties

spring.http.multipart.enabled=true

What should be my approach towards this file upload without using multipart?

This way, I'm able to uploading file using where I'm using multipart.

@RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
    public JsonNode dogCreation(HttpServletRequest httpRequest, @RequestParam(value = "picture", required = false) MultipartFile multipartFile,
                                @PathVariable("name") String name) throws IOException, InterruptedException {
        JSONObject response = new JSONObject();
        Dog dog = new Dog();
        String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";

        try {
            File file = new File(DOG_IMAGES_BASE_LOCATION);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        dog = dogService.getDogByName(name);
        if (dog == null) {
            if (!multipartFile.isEmpty()) {
                String multipartFileName = multipartFile.getOriginalFilename();
                String format = multipartFileName.substring(multipartFileName.lastIndexOf("."));
                try {
                    Path path = Paths.get(DOG_IMAGES_BASE_LOCATION + "/" + name + format);
                    byte[] bytes = multipartFile.getBytes();
                    File file = new File(path.toString());
                    file.createNewFile();
                    Files.write(path, bytes);
                    if (file.length() == 0) {
                        response = utility.createResponse(500, Keyword.ERROR, "Image upload failed");
                    } else {
                        String dbPath = path.toString().replace('\\', '/');
                        dog = new Dog();
                        dog.setName(name);
                        dog.setPicture(dbPath);
                        dog = dogService.dogCreation(dog);
                        response = utility.createResponse(200, Keyword.SUCCESS, "Image upload successful");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return objectMapper.readTree(response.toString());
    }

I want to do it without using multipart, what would you suggest?

This is what I've done till now to solve this

@RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
    public JsonNode dogCreation(HttpServletRequest httpRequest, @RequestParam("picture") String picture,
                                @PathVariable("name") String name) throws IOException, InterruptedException {
        JSONObject response = new JSONObject();
        Dog dog = new Dog();
        String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";

        try {
            File file = new File(DOG_IMAGES_BASE_LOCATION);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        dog = dogService.getDogByName(name);
        if (dog == null) {
            if (!picture.isEmpty()) {
                String dogPicture = picture;
                byte[] encodedDogPicture = Base64.encodeBase64(dogPicture.getBytes());
                String format = dogPicture.substring(picture.lastIndexOf("."));
                try {

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return objectMapper.readTree(response.toString());
    }

request body picture is given below

  • There are plenty of tutorials available on internet. you can refer any of them and in case you face any issue, ask a question on stackoverflow with your code snippet. – Smile Jan 07 '20 at 07:31
  • @Smile, Have upload code, would be great if you could suggest something. Haven't uploaded Service and repository portion, uploaded the controller portion only. –  Jan 07 '20 at 08:23
  • Why do you not want to use multipart? That is the standard way of uploading files with http. Otherwise maybe upload using websockets or encode the file to base64 and do a normal post? – DaafVader Jan 07 '20 at 08:28
  • @DaafVader It's a requirement that I'm facing –  Jan 07 '20 at 08:30

1 Answers1

0

I just have to say that this should probably only be used as a workaround.

On your frontend, convert the file to base64 in js:

const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt) {
   console.log(evt.target.result);
   //do POST here - something like this:
   $.ajax("/upload64", {
     method: "POST",
     contentType: "application/text"
     data: evt.target.result
   }
};

On the server with an example of a decoder - more decoding options here Decode Base64 data in Java

import sun.misc.BASE64Decoder;


@PostMapping("/upload64")
public String uploadBase64(@RequestBody String payload){
   BASE64Decoder decoder = new BASE64Decoder();
   byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
   //use your bytes
}
DaafVader
  • 1,735
  • 1
  • 14
  • 14
  • I'm getting this error "Failed to convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String': no matching editors or conversion strategy found" –  Jan 07 '20 at 09:27
  • Make sure your contentType header is set correctly in your post request. Edited with example above. – DaafVader Jan 07 '20 at 09:59
  • Key --> Content-Type Value --> application/json –  Jan 07 '20 at 10:05
  • Sir, how can I get binary data from post request that's been passed from postman? –  Jan 07 '20 at 10:23
  • Not sure what you mean. That seems like a completely new question though... – DaafVader Jan 16 '20 at 12:27