[英]How can I handle a situation where I need to send JSON and multipart/form-data in Spring boot
I would like to know a simple solution for receiving images and simple data in a single post using Spring.我想知道一个使用 Spring 在单个帖子中接收图像和简单数据的简单解决方案。 I am a beginner in Java so I would like to know the easy way.
我是 Java 的初学者,所以我想知道简单的方法。 I've used several backend frameworks and I've encountered this problem in all of them.
我使用了几个后端框架,并且在所有这些框架中都遇到了这个问题。
I have the following problem:我有以下问题:
I was receiving a multipart/form-data like this我收到了这样的多部分/表单数据
public CasaVenda storeCasaVendaOld(@RequestParam("dormitorios") Integer dormitorios, @RequestParam("preco") Double preco, @RequestParam("foto_1") MultipartFile foto_1){
I receive some numbers along with an image.我收到一些数字和图像。 This is a typical first attempt of beginner's implementation.Validate will require code to be writeen in the controller and I have to receive far more parameters than described here, so it's a bad implementation.
这是初学者实施的典型第一次尝试。验证将需要在 controller 中编写代码,并且我必须接收比这里描述的更多的参数,所以这是一个糟糕的实施。
I thought about receiving a model我想过收到 model
public CasaVenda storeCasaVenda(@Valid @RequestBody CasaVenda casa)
Now I can validate using annotations and so.现在我可以使用注释等进行验证。 The problem is with the file.
问题出在文件上。 Is there a simple solution to receive the file in one post request or should I split the process of seding the overall data and the files spareted?
是否有一种简单的解决方案可以在一个发布请求中接收文件,或者我应该拆分整个数据的处理过程和备用文件? I mean I can make the process of the resource creation two steps, first it enters the overall data and afterwards it includes the photos.
我的意思是我可以将资源创建过程分为两个步骤,首先它输入整体数据,然后它包括照片。
Its pretty easy to define an object:定义 object 非常容易:
public class MyObject {
private Integer dormitorios;
private Double preco;
...
getters/setters/constructors/etc.
...
// I'm not sure whether you can place a MultipartFile here as well to process image,
// however it doesn't make sense to validate it anyway
}
Then you can use this object in the controller, it will map all the query params to the fields of the object automatically by spring: Then you can use this object in the controller, it will map all the query params to the fields of the object automatically by spring:
public CasaVenda storeCasaVendaOld(MyObject myObject) {
}
Now, you can place Validation annotations inside MyObject and it will be validated, just do not use @RequestParam
annotation before the object...现在,您可以在 MyObject 中放置 Validation 注释,它将被验证,只是不要在 object 之前使用
@RequestParam
注释...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.