0

I am currently making a file upload within my spring boot project. I am using rest controller for my controller as that is what is written within the tutorial that I am using https://www.callicoder.com/spring-boot-file-upload-download-jpa-hibernate-mysql-database-example/

However, I found out that apparently rest controller unable to display HTML page based on what is written here: How to return a html page from a restful controller in spring boot?

Is there a way for displaying my HTML page while retaining the rest controller?

this is my controller

@RestController
public class RekonsiliasiController {

    private static final Logger logger = LoggerFactory.getLogger(RekonsiliasiController.class);

    @Autowired
    private DBFileStorageService dbFileStorageService;

    @RequestMapping("/rekonsiliasi")
    public String index() {
        System.err.println("MASUK PAK EKO OI");
        return "rekonsiliasi";
    }

    @PostMapping("/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        DBFile dbFile = dbFileStorageService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(dbFile.getId())
                .toUriString();

        return new UploadFileResponse(dbFile.getFileName(), fileDownloadUri,
                file.getContentType(), file.getSize());
    }

    @GetMapping("/downloadFile/{fileId}")
    public ResponseEntity<ByteArrayResource> downloadFile(@PathVariable String fileId) {
        // Load file from database
        DBFile dbFile = dbFileStorageService.getFile(fileId);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(dbFile.getFileType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
                .body(new ByteArrayResource(dbFile.getData()));
    }

}

and this is my rekonsiliasi.html

 <form method="POST" action="/uploadFile" enctype="multipart/form-data">
                                          <input type="file" name="file" /><br/><br/>
                                          <input type="submit" value="Submit" />
                                      </form>

This is what I get currently, a blank page with a simple text

enter image description here

UPDATE

I tried to divide between the index and the file upload to the following.

RekonsiliasiController.java

@Controller
public class RekonsiliasiController {

    @RequestMapping("/rekonsiliasi")
    public String index() {
        System.err.println("MASUK PAK EKO OI");
        return "rekonsiliasi";
    }

FileController.java

@RestController
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private DBFileStorageService dbFileStorageService;

    @PostMapping("/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        System.err.println("CEK");
        DBFile dbFile = dbFileStorageService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(dbFile.getId())
                .toUriString();

        return new UploadFileResponse(dbFile.getFileName(), fileDownloadUri,
                file.getContentType(), file.getSize());
    }


    @GetMapping("/downloadFile/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) {
        // Load file from database
        DBFile dbFile = dbFileStorageService.getFile(fileId);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(dbFile.getFileType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
                .body(new ByteArrayResource(dbFile.getData()));
    }

}

Now the HTML is showing perfectly fine but when I upload the file I got 403 Error. Before I tried to find the problem for this part, I'd like to know whether if there are some ways for displaying my HTML page while retaining the rest controller?

EDIT Delete the 'uploadMultipleFiles' method in FileController.Java and it still gets me 403 error

Gagak
  • 129
  • 2
  • 13

1 Answers1

1

First of all, in your code in the controller method uploadMultipleFiles, you are actually calling the controller method uploadFile directly by treating it just like another method which is not ideal. The fact that you need to recursively call another controller endpoint means that it is a design flaw in itself. So , try to remove this bit of code by providing the logic in service layer to handle this scenario .

Secondly , splitting the view controller and the rest controller into two separate classes is the right approach. The @RestController annotation is designed to serve json response by default that is why we have the @Controller annotation which serves both model and view. The response code 403 that you receive has nothing to do with this.

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39
  • Oh, it was my mistake when I made this post. I already delete the `uploadMultipleFiles` method and it still ends up with 403 error – Gagak May 19 '20 at 04:55
  • Have you added any logs or tried debugging to understand why it is returning 403. Is your request reaching your endpoint ? – Ananthapadmanabhan May 19 '20 at 04:56
  • As I submit the uploaded file, it is successfully lead the link to `/uploadFile` however apparently after I check it again - Apparently, it didn't enter the method of `uploadFile` – Gagak May 19 '20 at 05:00
  • Could you check the request that yoiu are initiating to verify that the multipart file and other parameters are correct in the request ? – Ananthapadmanabhan May 19 '20 at 05:50
  • Is there a way to check it? Since I have tried to put `System.err.println("Check")` in the very first line of my method. It doesn't show in my console despite it is directed to `/uploadFile` for the URL – Gagak May 19 '20 at 06:59
  • @Gagak Are you using spring security ? If yes allow the url mapping . You can enable and check the springboot access logs to understand the request recieved by the endpoint . It will help you understand if there is any issue with your request. – Ananthapadmanabhan May 19 '20 at 07:44
  • Oh, I tried to disable the CSRF token in the security and it works. However, I am not sure if it is advisable to do that or not. – Gagak May 19 '20 at 07:53
  • 1
    @Gagak The csrf token needs to be added in the request as well if you enable it in security. It will fix your issues. – Ananthapadmanabhan May 19 '20 at 08:22