Java File upload example

 @PostMapping(value = "/api/dashboard/upload",consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })

    public FileDataModel upload(@RequestPart MultipartFile file) throws IOException {

        String test="";

        FileDataModel fileDataModel = new FileDataModel();

        if(!file.getOriginalFilename().contains(".json")){

            fileDataModel.setInvalidData(false);

            fileDataModel.setInvalidFile(true);

            return fileDataModel;

        }

        BufferedInputStream fileStream = new BufferedInputStream(file.getInputStream());

        FileOutputStream fileOutputStream = null;

        try {

            fileOutputStream = new FileOutputStream(exportPath + "test.json");

        } catch (Exception e) {

            throw new RuntimeException("Could not found the file in the location", e);

        }

        byte[] buf = new byte[1024];

        int len;

        InputStream fileInputStream = file.getInputStream();

        try {

            while ((len = fileInputStream.read(buf)) > 0) {

                fileOutputStream.write(buf, 0, len);


            }

            fileInputStream.close();

            fileOutputStream.close();

        } catch (Exception e) {

            throw new RuntimeException("Could not found the file in the location", e);

        }

        test = Files.readString(Path.of(exportPath + "test.json"));

        System.out.println(test+"--------------->>>>");

        if(result.equalsIgnoreCase("INVALID")){

            fileDataModel.setInvalidData(true);

            fileDataModel.setInvalidFile(false);

        }

        return fileDataModel;

    } 



Happy Learning 😜

Comments

Popular Posts