将MultipartFile转换为字节数组在Spring Boot中

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

How to convert the MultipartFile into byte array in spring Boot

问题

我在一个Spring Boot项目中使用PostgreSQL作为数据库,需要创建一个事件并保存事件的详细信息以及事件传单。我将事件传单作为multipartFile传递给eventController,在Service类中将其转换为字节数组使用getBytes()方法。我已经按如下方式实现了代码,并尝试使用Postman发送请求。

这是我的Event实体:

  1. package com.example.attendingsystembackend.model;
  2. import jakarta.persistence.Entity;
  3. import jakarta.persistence.GeneratedValue;
  4. import jakarta.persistence.Id;
  5. import jakarta.persistence.Lob;
  6. import jakarta.validation.constraints.NotBlank;
  7. import jakarta.validation.constraints.NotNull;
  8. import org.hibernate.annotations.GenericGenerator;
  9. import java.time.LocalDateTime;
  10. @Entity
  11. public class Event {
  12. @Id
  13. @GeneratedValue(generator = "system-uuid")
  14. @GenericGenerator(name="system-uuid",strategy = "uuid")
  15. private String id;
  16. @NotBlank(message = "Event name cannot be blank")
  17. private String eventName;
  18. private String eventType;
  19. @NotBlank(message = "Event location cannot be blank")
  20. private String location;
  21. @NotNull
  22. private LocalDateTime startTime;
  23. @NotNull
  24. private LocalDateTime endTime;
  25. @Lob
  26. private byte[] eventFlyer;
  27. // ... Getters and setters
  28. }

这是我的事件服务类:

  1. package com.example.attendingsystembackend.service;
  2. import com.example.attendingsystembackend.model.Event;
  3. import com.example.attendingsystembackend.repository.EventRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.web.multipart.MultipartFile;
  7. import java.io.IOException;
  8. @Service
  9. public class EventService {
  10. private final EventRepository eventRepository;
  11. @Autowired
  12. public EventService(EventRepository eventRepository) {
  13. this.eventRepository = eventRepository;
  14. }
  15. public void saveEvent(MultipartFile file, Event event) throws IOException {
  16. Event newEvent = new Event();
  17. // 设置事件属性...
  18. if (file != null && !file.isEmpty()) {
  19. byte[] fileBytes = file.getBytes();
  20. newEvent.setEventFlyer(fileBytes);
  21. } else {
  22. newEvent.setEventFlyer(null);
  23. }
  24. eventRepository.save(newEvent);
  25. }
  26. }

这是我的事件控制器类:

  1. package com.example.attendingsystembackend.controller;
  2. import com.example.attendingsystembackend.model.Event;
  3. import com.example.attendingsystembackend.service.EventService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.multipart.MultipartFile;
  12. @RestController
  13. @RequestMapping("api/event")
  14. public class EventController {
  15. private final EventService eventService;
  16. @Autowired
  17. public EventController(EventService eventService) {
  18. this.eventService = eventService;
  19. }
  20. @PostMapping(value="saveEvent")
  21. public ResponseEntity<String> saveEvent(@RequestParam(value = "file", required = false) MultipartFile file, Event event) {
  22. try {
  23. eventService.saveEvent(file, event);
  24. return ResponseEntity.status(HttpStatus.OK)
  25. .body(String.format("Event saved successfully with file: %s", file.getOriginalFilename()));
  26. } catch (Exception e) {
  27. return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
  28. .body(String.format("Could not save the event: %s!", e));
  29. }
  30. }
  31. }

问题似乎出现在将MultiPartFile转换为byte[]时。这个错误可能是因为类型不匹配。确保MultiPartFile的正确处理以转换为byte[]。希望这可以帮助解决您的问题。

英文:

I'm working on a spring boot project where I use postgresql as my database. In my project I need to create an event and save the details of the event along with the event flyer. I'm passing the event flyer to the eventController as a multipartFile and in the Service class I will convert it to a byte array using method getBytes() . I implemented the code as follows and tried to send a request using postman.

This is my Event Entity :

  1. `package com.example.attendingsystembackend.model;
  2. import jakarta.persistence.Entity;
  3. import jakarta.persistence.GeneratedValue;
  4. import jakarta.persistence.Id;
  5. import jakarta.persistence.Lob;
  6. import jakarta.validation.constraints.NotBlank;
  7. import jakarta.validation.constraints.NotNull;
  8. import org.hibernate.annotations.GenericGenerator;
  9. import java.time.LocalDateTime;
  10. @Entity
  11. public class Event {
  12. @Id
  13. @GeneratedValue(generator = &quot;system-uuid&quot;)
  14. @GenericGenerator(name=&quot;system-uuid&quot;,strategy = &quot;uuid&quot;)
  15. private String id;
  16. @NotBlank(message = &quot;Event name cannot be blank&quot;)
  17. private String eventName;
  18. private String eventType;
  19. @NotBlank(message = &quot;Event location cannot be blank&quot;)
  20. private String location;
  21. @NotNull
  22. private LocalDateTime startTime;
  23. @NotNull
  24. private LocalDateTime endTime;
  25. @Lob
  26. private byte[] eventFlyer;
  27. public String getId() {
  28. return id;
  29. }
  30. public void setId(String id) {
  31. this.id = id;
  32. }
  33. public String getEventName() {
  34. return eventName;
  35. }
  36. public void setEventName(String eventName) {
  37. this.eventName = eventName;
  38. }
  39. public String getEventType() {
  40. return eventType;
  41. }
  42. public void setEventType(String eventType) {
  43. this.eventType = eventType;
  44. }
  45. public String getLocation() {
  46. return location;
  47. }
  48. public void setLocation(String location) {
  49. this.location = location;
  50. }
  51. public LocalDateTime getStartTime() {
  52. return startTime;
  53. }
  54. public void setStartTime(LocalDateTime startTime) {
  55. this.startTime = startTime;
  56. }
  57. public LocalDateTime getEndTime() {
  58. return endTime;
  59. }
  60. public void setEndTime(LocalDateTime endTime) {
  61. this.endTime = endTime;
  62. }
  63. public byte[] getEventFlyer() {
  64. return eventFlyer;
  65. }
  66. public void setEventFlyer(byte[] eventFlyer) {
  67. this.eventFlyer = eventFlyer;
  68. }
  69. }`

And this is my event service class:

  1. package com.example.attendingsystembackend.service;
  2. import com.example.attendingsystembackend.model.Event;
  3. import com.example.attendingsystembackend.repository.EventRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.web.multipart.MultipartFile;
  7. import java.io.IOException;
  8. @Service
  9. public class EventService {
  10. private final EventRepository eventRepository;
  11. @Autowired
  12. public EventService(EventRepository eventRepository) {
  13. this.eventRepository = eventRepository;
  14. }
  15. public void saveEvent(MultipartFile file, Event event) throws IOException {
  16. Event newEvent=new Event();
  17. newEvent.setEventName(event.getEventName());
  18. newEvent.setEventType(event.getEventType());
  19. newEvent.setLocation(event.getLocation());
  20. newEvent.setStartTime(event.getStartTime());
  21. newEvent.setEndTime(event.getEndTime());
  22. if(file!=null &amp;&amp; !file.isEmpty()) {
  23. byte[] fileBytes = file.getBytes();
  24. newEvent.setEventFlyer(fileBytes);
  25. }else{
  26. newEvent.setEventFlyer(null);
  27. }
  28. eventRepository.save(newEvent);
  29. }
  30. }

And here is my event controller class:

  1. package com.example.attendingsystembackend.controller;
  2. import com.example.attendingsystembackend.model.Event;
  3. import com.example.attendingsystembackend.service.EventService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import org.springframework.web.multipart.MultipartFile;
  12. @RestController
  13. @RequestMapping(&quot;api/event&quot;)
  14. public class EventController {
  15. private final EventService eventService;
  16. @Autowired
  17. public EventController(EventService eventService) {
  18. this.eventService = eventService;
  19. }
  20. @PostMapping(value=&quot;saveEvent&quot;)
  21. public ResponseEntity&lt;String&gt; saveEvent(@RequestParam(value = &quot;file&quot;, required = false) MultipartFile file, Event event) {
  22. try {
  23. eventService.saveEvent(file,event);
  24. return ResponseEntity.status(HttpStatus.OK)
  25. .body(String.format(&quot;Event saved succesfully with file: %s&quot;, file.getOriginalFilename()));
  26. } catch (Exception e) {
  27. return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
  28. .body(String.format(&quot;Could not save the event: %s!&quot;, e));
  29. }
  30. }
  31. }

And tried to send request using postman as follows:

将MultipartFile转换为字节数组在Spring Boot中

But Unfortunately I'm getting the following error:

  1. Validation failed for argument [1] in public org.springframework.http.ResponseEntity&lt;java.lang.String&gt; com.example.attendingsystembackend.controller.EventController.saveEvent(org.springframework.web.multipart.MultipartFile,com.example.attendingsystembackend.model.Event): [Field error in object &#39;event&#39; on field &#39;eventFlyer&#39;: rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@42f6b750]; codes [typeMismatch.event.eventFlyer,typeMismatch.eventFlyer,typeMismatch.[B,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [event.eventFlyer,eventFlyer]; arguments []; default message [eventFlyer]]; default message [Failed to convert property value of type &#39;org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile&#39; to required type &#39;byte[]&#39; for property &#39;eventFlyer&#39;; Cannot convert value of type &#39;org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile&#39; to required type &#39;byte&#39; for property &#39;eventFlyer[0]&#39;: PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type &#39;org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile&#39;]] ]

As I feel the error occured when converting MultiPartFile to byte[] Can someone help me with this issue? What is the mistake I have done here? Thank you in advance.

答案1

得分: 1

1). 在您的POST方法中,您发送了一个多部分文件和事件类,但您将它们发送为@Request参数。而不是这样做:

  1. @PostMapping(value="saveEvent")
  2. public ResponseEntity<String> saveEvent(@RequestPart("file") MultipartFile file, @RequestPart("body") Event event) // 也可以将JSON作为字符串值传递,然后映射为对象

2). 您从Postman发送请求应该像这样(示例):

将MultipartFile转换为字节数组在Spring Boot中

英文:

I have noticed two things here,

1). In your post method you have sending a multipart file and event class. but you sending them as @Request param.. instead do this

  1. @PostMapping(value=&quot;saveEvent&quot;)
  2. public ResponseEntity&lt;String&gt; saveEvent(@RequestPart(&quot;file&quot;) MultipartFile file, @RequestPart(&quot;body&quot;) Event event) // you can also pass json as string value and then map into objects

2). your request from the postman should be like this.(sample)

将MultipartFile转换为字节数组在Spring Boot中

huangapple
  • 本文由 发表于 2023年4月10日 18:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976409.html
匿名

发表评论

匿名网友

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

确定