Вы здесь:

Используется Java 11, Spring Boot, Themeleaf, Bootstrap.
Ссылка на репозиторий: FileUploadExample

Так выглядит страница загрузки файлов:

fileupload


Выбранный файл будет сохранен в папку на сервере. Папка для хранения задается на backend.

HomePage.html:

<form method="POST" action="/upload"
      onsubmit="return Validate(this);" enctype="multipart/form-data">
    <div class="col-md-2">
        <b>Загрузка файлов</b>
    </div>
    <label for="choose_file" class="col-md-2 btn btn-primary" style="height: 2.6em; margin-right: 1em;">1. Выбрать файл</label>
    <input id="choose_file" type="file" name="file"  style="display: none;"  accept=".csv" value="Выбрать файл:"/>
     
    <input type="submit" class="col-md-2 btn btn-primary"   style="height: 2.6em;" value="2. Загрузить"/>
</form>

 

Frontend

Ключевые элементы формы:

<form method="POST" action="/upload"
      onsubmit="return Validate(this);" enctype="multipart/form-data">

method="POST"
action="/upload" - метод на backend для приема файла.
Validate(this); - проверка расширения файла. Функция возвращает true/false.
enctype="multipart/form-data" - формат передачи данных для POST запроса.

Backend

https://github.com/cherepakhin/FileUploadExample/blob/main/src/main/java/com/programinjava/learn/controller/UploadController.java

@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, ModelMap modelMap) {
    logger.info("POST /upload");
    logger.info("Multipart name: {}", file.getName());
    logger.info("Multipart OriginalFilename={}", file.getOriginalFilename());

    if (file.isEmpty()) {
        redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
        return "redirect:uploadStatus";
    }

    logger.info("Домашний каталог пользователя: {}", userHomeDir); //  /home/vasi
    logger.info("Catalog for save: {}", catalogForSave);

    String fileName = file.getOriginalFilename();
    logger.info("FileName : {}", fileName);

    // save file to disk
    if (!storageService.store(file, userHomeDir + catalogForSave, fileName)) {
        redirectAttributes.addFlashAttribute("message", "Error occurred while uploading the file");
        redirectAttributes.addFlashAttribute("status", "false");
        return "redirect:/uploadStatus";
    }
    String catalog = userHomeDir + catalogForSave;
    logger.info("last saved file: {}/{}", catalog, fileName);

    List listLoadedFiles = storageService.getHistoryLoadedFiles();
    redirectAttributes.addFlashAttribute("listLoadedFiles", listLoadedFiles);

    redirectAttributes.addFlashAttribute("fileName", fileName);
    redirectAttributes.addFlashAttribute("message", "Загружен файл '" + fileName + "'");
    redirectAttributes.addFlashAttribute("status", "true");
    redirectAttributes.addFlashAttribute("getLastUploaded", storageService.getHistoryLoadedFiles());

    return "redirect:/uploadStatus";
}

 

Ссылки