如何从requestParam接收带有图像的实体

huangapple go评论92阅读模式
英文:

how to receive an entity with image from requestParam

问题

I'm trying to save an entity (Product) with many attributes, one of them, the picture. And I don't know how to get both (entity and image) in the controller.

  1. @PostMapping
  2. public ResponseEntity<?> create(@Valid @RequestBody Product product,
  3. BindingResult result, @RequestParam("imageData") MultipartFile imageData);

If I put it this way I get an "Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'multipart/form-data;boundary=--------------------------889210147211052471233495;charset=UTF-8'" error.

If I only get the @RequestParam, because I suppose, I cannot use two both Request at the same time, I don't know how to send both, product and image.
And much less, I don't know yet how to send this information from the front-end in react.

  1. export const ProductForm = ({ productSelected }) => {
  2. const initialProductForm = {
  3. id: 0,
  4. productName: '',
  5. description: '',
  6. image: " ",
  7. price: 0,
  8. }
  9. const { initialProductForm, handlerAddProduct, errors } = useProducts();
  10. const [productForm, setProductForm] = useState(initialProductForm);
  11. let { id, productName, description, image, price } = productForm;
  12. const onInputChange = ({ target }) => {
  13. const { name, value } = target;
  14. setProductForm({
  15. ...productForm,
  16. [name]: value,
  17. })
  18. }
  19. const handleSubmit = (event) => {
  20. event.preventDefault();
  21. imageData.append('product', productForm);
  22. imageData.append('imageName', imageName);
  23. imageData.append('imageData', imageData);
  24. handlerAddProduct(productForm);
  25. }
  26. const handleChange = event => {
  27. setImageName(event.target.value)
  28. };
  29. const [imageData, setImageData] = useState(null);
  30. const [imageName, setImageName] = useState("");
  31. return (
  32. <>
  33. <form onSubmit={handleSubmit} method="POST" encType="application/json">
  34. <input
  35. className="form-control my-3 w-75"
  36. placeholder="ProductName"
  37. name="productName"
  38. value={productName}
  39. onChange={onInputChange}
  40. />
  41. <p className="text-danger">{errors?.productName}</p>
  42. <input type="number"
  43. className="form-control my-3 w-75"
  44. placeholder="Price"
  45. name="price"
  46. value={price}
  47. onChange={onInputChange}
  48. />
  49. <p className="text-danger">{errors?.price}</p>
  50. <input
  51. className="form-control my-3 w-75"
  52. placeholder="Description"
  53. name="description"
  54. value={description}
  55. onChange={onInputChange}
  56. />
  57. <p className="text-danger">{errors?.description}</p>
  58. <input
  59. accept="image/*"
  60. id="upload-profile-image"
  61. name="image"
  62. type="file"
  63. onChange={handleUploadClick}
  64. />
  65. <label htmlFor="upload-profile-image">
  66. <Button
  67. variant="contained"
  68. color="primary"
  69. component="span"
  70. >
  71. Change Image
  72. </Button>
  73. </label>
  74. <TextField
  75. fullWidth
  76. label="Image Name"
  77. margin="dense"
  78. name="name"
  79. onChange={handleChange}
  80. required
  81. value={imageName}
  82. variant="outlined"
  83. />
  84. <input
  85. type="hidden"
  86. name="id"
  87. value={id}
  88. />
  89. <button
  90. className="btn btn-primary"
  91. type="submit">
  92. {id > 0 ? 'Update' : 'Create'}
  93. </button>
  94. </form>
  95. </>
  96. )
  97. }

ProductService:

  1. export const save = async (product) => {
  2. try {
  3. return await usersApi.post(`${BASE_URL}/products/addProduct`, product, imageData);
  4. } catch (error) {
  5. console.log("error " + error);
  6. throw error;
  7. }
  8. }

I can't make the controller work even from Postman. Postman

And of course I'm completely lost on the React Front-end.

Please. Help 如何从requestParam接收带有图像的实体

Thanks a lot.

To get the product and the image to do this: product.setImage() = image.getBytes();

英文:

I'm trying to save an entity (Product) with many attributes, one of them , the picture. And I don't know how to get both (entity and image) in the controller.

  1. @PostMapping
  2. public ResponseEntity&lt;?&gt; create(@Valid @RequestBody Product product,
  3. BindingResult result, @RequestParam(&quot;imageData&quot;) MultipartFile imageData);

If i put it this way I get an "Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'multipart/form-data;boundary=--------------------------889210147211052471233495;charset=UTF-8' is not supported]" error.

If I only get the @RequestParam, because I suppose, I cannot use two both Request at the same time, I don't know how to send both, product and image.
And much less, I don't know yet how to send this information from the front-end in react.

  1. export const ProductForm = ({ productSelected }) =&gt; {
  2. const initialProductForm = {
  3. id: 0,
  4. productName: &#39;&#39;,
  5. description: &#39;&#39;,
  6. image: &quot; &quot;,
  7. price: 0,
  8. }
  9. const { initialProductForm, handlerAddProduct, errors } = useProducts();
  10. const [productForm, setProductForm] = useState(initialProductForm);
  11. let { id, productName, description, image, price } = productForm;
  12. const onInputChange = ({ target }) =&gt; {
  13. const { name, value } = target;
  14. setProductForm({
  15. ...productForm,
  16. [name]: value,
  17. })
  18. }
  19. const handleSubmit = (event) =&gt; {
  20. event.preventDefault();
  21. imageData.append(&#39;product&#39;,productForm);
  22. imageData.append(&#39;imageName&#39;, imageName);
  23. imageData.append(&#39;imageData&#39;, imageData);
  24. handlerAddProduct(productForm);
  25. }
  26. const handleChange = event =&gt; {
  27. setImageName(event.target.value)
  28. };
  29. const [imageData, setImageData] = useState(null);
  30. const [imageName, setImageName] = useState(&quot;&quot;);
  31. return (
  32. &lt;&gt;
  33. &lt;form onSubmit={handleSubmit} method=&quot;POST&quot; encType=&quot;application/json&quot;&gt;
  34. &lt;input
  35. className=&quot;form-control my-3 w-75&quot;
  36. placeholder=&quot;ProductName&quot;
  37. name=&quot;productName&quot;
  38. value={productName}
  39. onChange={onInputChange}
  40. /&gt;
  41. &lt;p className=&quot;text-danger&quot;&gt;{errors?.productName}&lt;/p&gt;
  42. &lt;input type=&quot;number&quot;
  43. className=&quot;form-control my-3 w-75&quot;
  44. placeholder=&quot;Price&quot;
  45. name=&quot;price&quot;
  46. value={price}
  47. onChange={onInputChange}
  48. /&gt;
  49. &lt;p className=&quot;text-danger&quot;&gt;{errors?.price}&lt;/p&gt;
  50. &lt;input
  51. className=&quot;form-control my-3 w-75&quot;
  52. placeholder=&quot;Description&quot;
  53. name=&quot;description&quot;
  54. value={description}
  55. onChange={onInputChange}
  56. /&gt;
  57. &lt;p className=&quot;text-danger&quot;&gt;{errors?.description}&lt;/p&gt;
  58. &lt;input
  59. accept=&quot;image/*&quot;
  60. id=&quot;upload-profile-image&quot;
  61. name=&quot;image&quot;
  62. type=&quot;file&quot;
  63. onChange={handleUploadClick}
  64. /&gt;
  65. &lt;label htmlFor=&quot;upload-profile-image&quot;&gt;
  66. &lt;Button
  67. variant=&quot;contained&quot;
  68. color=&quot;primary&quot;
  69. component=&quot;span&quot;
  70. &gt;
  71. Change Image
  72. &lt;/Button&gt;
  73. &lt;/label&gt;
  74. &lt;TextField
  75. fullWidth
  76. label=&quot;Image Name&quot;
  77. margin=&quot;dense&quot;
  78. name=&quot;name&quot;
  79. onChange={handleChange}
  80. required
  81. value={imageName}
  82. variant=&quot;outlined&quot;
  83. /&gt;
  84. &lt;input
  85. type=&quot;hidden&quot;
  86. name=&quot;id&quot;
  87. value={id}
  88. /&gt;
  89. &lt;button
  90. className=&quot;btn btn-primary&quot;
  91. type=&quot;submit&quot;&gt;
  92. {id &gt; 0 ? &#39;Update&#39; : &#39;Create&#39;}
  93. &lt;/button&gt;
  94. &lt;/form&gt;
  95. &lt;/&gt;
  96. )
  97. }

ProductService:

  1. export const save = async (product) =&gt; {
  2. try {
  3. return await usersApi.post(`${BASE_URL}/products/addProduct`, product, imageData);
  4. } catch (error) {
  5. console.log(&quot;errrooorrr &quot; + error);
  6. throw error;
  7. }
  8. }

I can't make the controller work even from Postman. Postman

And of course I'm complete lost from React Front-end.

Please. Help 如何从requestParam接收带有图像的实体

Thanks a lot.

To get the product and the image to do this: product.setImage()= image.getBytes();

答案1

得分: 1

这是您要翻译的内容:

  1. 尝试接收 JSON RequestBody 和图像/文件的同一请求是否可行还不确定。但您可以尝试以下方法:

    1. 将图像转换为 base64 字符串并将其添加到 JSON 请求中。这样,您可以将请求作为 RequestBody 接收,然后从中读取 base64 图像数据并将其转换为图像。

    示例:

    请求

    1. {
    2. "productName" : "Xbox",
    3. "description" : "Xbox",
    4. "price" : "500",
    5. "imageData" : "图像的 base64 字符串数据在这里"
    6. }

    接收请求

    1. @PostMapping("/json")
    2. public void readJsonRequest(@RequestBody(required = true) String jsonRequest) {
    3. JSONObject object = new JSONObject(jsonRequest);
    4. String productName = object.getString("productName");
    5. String imageData = object.getString("imageData");
    6. // 将 imageData 从 base64 转换为图像
    7. }
  2. 以 ContentType: multipart/form-data 的形式发送请求。这样,您可以添加键,并使用 RequestParams 和 MultipartFile 接收它们。

    示例

    请求

    1. Key Value
    2. productName Xbox
    3. description Xbox
    4. price 500
    5. imageFile 选择的文件(.png、.jpg 等)

    接收请求

    1. @PostMapping("/request")
    2. public void readRequest(
    3. @RequestParam(value = "productName", required = true) String productName,
    4. @RequestParam(value = "description", required = true) String description,
    5. @RequestParam(value = "price", required = true) String price,
    6. @RequestParam(value = "imageFile", required = true) MultipartFile imageFile) {
    7. }

要将 JSON 对象作为实体发送,请确保 JSON 请求中的键/属性与实体类中的字段名称匹配。例如,JSON 请求中的 "productName" 键应与 Product 实体类中的 "private String productName" 匹配。

要接收它:

  1. public ResponseEntity<?> create(@Valid @RequestBody Product product, BindingResult result) {
  2. }
英文:

No sure if it's possible to receive JSON RequestBody and image/file in same request. But you can try approaches below

  1. Convert image to base64 string and add it to json request. This way you will be able to receive request as RequestBody from which you can read base64 image data and convert it to image.

Eg.

Request

  1. {
  2. &quot;productName&quot; : &quot;Xbox&quot;,
  3. &quot;description&quot; : &quot;Xbox&quot;,
  4. &quot;price&quot; : &quot;500&quot;,
  5. &quot;imageData&quot; : &quot;image base64 string data here&quot;
  6. }

Receive request

  1. @PostMapping(&quot;/json&quot;)
  2. public void readJsonRequest(@RequestBody(required = true) String jsonRequest) {
  3. JSONObject object = new JSONObject(jsonRequest);
  4. String productName = object.getString(&quot;productName&quot;);
  5. String imageData = object.getString(&quot;imageData&quot;);
  6. //convert imageData from base64 to image
  7. }
  1. Send request as ContentType: multipart/form-data. This way you can add keys and receive them using RequestParams & MultipartFile

E.g
Request

  1. Key value
  2. productName Xbox
  3. description Xbox
  4. price 500
  5. imageFile selected file (.png, .jpg etc)

Receive request

  1. @PostMapping(&quot;/request&quot;)
  2. public void readRequest(@RequestParam(value = &quot;productName&quot;, required = true) String productName,
  3. @RequestParam(value = &quot;description&quot;, required = true) String description,
  4. @RequestParam(value = &quot;price&quot;, required = true) String price,
  5. @RequestParam(value = &quot;imageFile&quot;, required = true) MultipartFile imageFile) {
  6. }

To send Json object as entity, ensure keys/properties in json request matches fields names in your entity class. Eg productName key in json request should match private String productName in Product entity class.

To receive it

  1. public ResponseEntity&lt;?&gt; create(@Valid @RequestBody Product product,
  2. BindingResult result) {
  3. }

huangapple
  • 本文由 发表于 2023年7月11日 00:36:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定