Search code examples
htmlspringspring-bootthymeleaf

Springboot uploading files Required request part 'file' is not present


I'm trying to upload a image as a string field in an advert,but when adding a file to the body i got this error: "exception": "org.springframework.web.multipart.support.MissingServletRequestPartException", "message": "Required request part 'file' is not present". I looked here for answers on this problem, but nothing helped me. I will be glad of any help.

My controller:

    @Controller
    @RequestMapping("/adverts")
    public class AdvertController {

    private AdvertService advertService;
    private FileUploadService fileUploadService;

    public AdvertController(AdvertService advertService, FileUploadService fileUploadService) {
        this.advertService = advertService;
        this.fileUploadService = fileUploadService;
    }

    @GetMapping("/showFormForAdd")
    public String showFormForAdd(MultipartFile file, Model theModel) throws IOException {

        Advert theAdvert = new Advert();
        theModel.addAttribute("advert", theAdvert);

        return "adverts/advert-form";
    }    

    @PostMapping("/save")
    public String saveAdvert(@RequestParam("file") MultipartFile file,
                             @AuthenticationPrincipal Account user,
                             @Valid @ModelAttribute("advert") Advert theAdvert,
                             BindingResult bindingResult) throws IOException {

        if (bindingResult.hasErrors()) {
            return "adverts/advert-form";
        } else {

            String filepath = fileUploadService.upload(file);
            theAdvert.setFilename(filepath);

            advertService.save(user, theAdvert);
        }
        return "redirect:/adverts/list";
    }
  }

My service:


@Service
public class FileUploadServiceImpl implements FileUploadService {

    private String UPLOADED_FOLDER = "/images/";
@Override
    public String upload(MultipartFile file) {
        System.out.println(file);
        if(file.isEmpty())
            return null;

        String fileName = null;
        try {
            fileName =  generateFileName(Objects.requireNonNull(file.getOriginalFilename()));

            byte[]bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + fileName);
            Files.write(path, bytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/resources/" + fileName;
    }

    private String generateFileName(String file){
        String ext = file.substring(file.lastIndexOf("."));
        return System.currentTimeMillis() + ext;
    }
}

My html form for input:

<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

</head>

<body>

<div class="container">

    <h3>Объявления о продаже недвижимости</h3>
    <hr>

    <p class="h4 mb-4">Добавить новое объявление в систему</p>

    <form action="#" th:action="@{/adverts/save}"
          th:object="${advert}" method="POST" enctype="multipart/form-data">


        <!-- Add hidden form field to handle update -->
        <input type="hidden" th:field="*{id}" />

        <input type="text" th:field="*{title}"
               class="form-control mb-4 col-4" placeholder="Название"/>
            <p th:if="${#fields.hasErrors('title')}" th:errors="*{title}" class="alert alert-danger col-4" >Title Error</p>

        <input type="file" name="file_upload"
               class="form-control mb-4 col-4" placeholder="Изображение">

<!--        <input type="file" name="file"/>-->
<!--        <input type="hidden" class="form-control" th:field="*{photo}" placeholder="Enter Image"/>-->

        <input type="text" th:field="*{price}"
               class="form-control mb-4 col-4" placeholder="Цена">
        <p th:if="${#fields.hasErrors('price')}" th:errors="*{price}" class="alert alert-danger col-4" >Price Error</p>

        <input type="text" th:field="*{description}"
               class="form-control mb-4 col-4" placeholder="Описание">
        <p th:if="${#fields.hasErrors('description')}" th:errors="*{description}" class="alert alert-danger col-4" >Description Error</p>

        <button type="submit" class="btn btn-info col-2">Добавить</button>

    </form>

    <a th:href="@{/adverts/list}">Назад к списку объявлений</a>

</div>
</body>

</html>


Solution

  • Change

    <input type="file" name="file_upload" class="form-control mb-4 col-4" placeholder="Изображение">
    

    To

    <input type="file" name="file" class="form-control mb-4 col-4" placeholder="Изображение">
    

    Your controller expects a param file, but from html you are sending file_upload. Thats why spring shows error message "Required request part 'file' is not present"