public class exampleDto {
// валидация поля
private MultipartFile file;
// валидация поля
private List<childDto> childList;
}
@PostMapping(path = "/create")
public ResponseDto create(@Validated(OnCreate.class) @ModelAttribute exampleDto dto) throws IOException {
return mapper.toDto(service.create(dto));
}
let childList = [
{field1: 'text', field2: 'text'},
{field1: 'text', field2: 'text'},
...
]
@RequestMapping(value = "/save", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void save(
@RequestPart("product") final ProductCreateRequest productCreateRequest,
@RequestPart("images") final List<MultipartFile> images) {
Product product = new Product();
System.out.println(productCreateRequest);
product.setBrand(productCreateRequest.getBrand());
product.setCategories(productCreateRequest.getCategories());
product.setPrice(productCreateRequest.getPrice());
product.setQuantity(productCreateRequest.getQuantity());
product.setNameModel(productCreateRequest.getNameModel());
int iterator = 0;
String resoursePath = new ClassPathResource("/src/main/resources/images/").getPath();
for (MultipartFile image : images) {
String imageName = product.getNameModel()+ "-" + iterator + "-" + image.getOriginalFilename();
System.out.println(imageName);
try {
image.transferTo(Paths.get(resoursePath + imageName));
} catch (IOException e) {
e.printStackTrace();
return;
}
product.getImage().add(new Image(null, imageName));
}
System.out.println(product);
productService.save(product);
}
// Получение файлов
const handleFileSelect = (event) => {
// Получить выбранные файлы
const files = event.target.files;
// Сохранить файлы в переменной
selectedFiles = files;
};
// Отправка на сервер
saveProduct(product: any, images: any) {
const formData = new FormData();
formData.append("product", JSON.stringify(product));
for (let i = 0; i < images.length; i++) {
console.log(images);
formData.append("images", images[i]);
}
$axios({
method: "post",
url: "/product/save",
data: formData,
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
console.log(response);
// Обработка успешного ответа
})
.catch((error) => {
console.log(error);
// Обработка ошибки
});
},