我在Spring Boot的電子商務應用程序中有一個窗體。它運作良好。 我的控制器部分看起來是這樣的:帶有很多輸入的彈簧啓動窗體+上傳
@RequestMapping(value = "/admin/add",method = RequestMethod.POST)
public String adminAddProductSubmit(@ModelAttribute(value = "product") Product product){
productServiceJpa.addProduct(product);
return "/admin/added";
}
現在我要上傳輸入添加到上傳圖像。有一個問題。 我試過這個:
@RequestMapping(value = "/admin/add",method = RequestMethod.POST)
public String adminAddProductSubmit(final @ModelAttribute(value = "product") Product product, final @RequestAttribute(value = "image") MultipartFile uploadingFile){
File file = new File(uploadingdir + uploadingFile.getOriginalFilename());
try {
uploadingFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
productServiceJpa.addProduct(product);
}
不幸的是,它不起作用。
我的形式:
<form th:action="@{/admin/add}" th:object="${product}" class="form-horizontal" method="post" enctype="multipart/form-data">
<h2>Nazwa przedmiotu</h2>
<div class="form-group">
<label for="title" class="col-sm-3 control-label">Tytuł</label>
<div class="col-sm-9">
<input type="text" th:field="*{title}" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="category" class="col-sm-3 control-label">Kategoria</label>
<div class="col-sm-9">
<input type="text" th:field="*{category}" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="amount" class="col-sm-3 control-label">Ilość</label>
<div class="col-sm-9">
<input type="text" th:field="*{amount}" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="shortDesc" class="col-sm-3 control-label">Krótki opis</label>
<div class="col-sm-9">
<input type="text" th:field="*{shortDesc}" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-3 control-label">Opis</label>
<div class="col-sm-9">
<input type="text" th:field="*{description}" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="price" class="col-sm-3 control-label">Cena</label>
<div class="col-sm-9">
<input type="text" th:field="*{price}" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="image" class="col-sm-3 control-label">
<div class="col-sm-9">
<input type="file" th:field="*{image}" class="custom-file-input"/>
<span class="custom-file-control"></span>
</div>
</label>
</div>
<input type="submit" class="btn btn-info" value="Dodaj"/>
</form>
你能告訴我怎麼把我的對象,並把它在@ModelAttribute和文件輸入獲取文件?
在Spring Boot文檔中有許多教程f.e,但只有上傳表單。我想要一個包含許多文本輸入和文件輸入的表單。
'@ RequestAttribute'!='@ RequestParam' ...使用正確的註釋。 –