英文:
How to convert the MultipartFile into byte array in spring Boot
问题
我在一个Spring Boot项目中使用PostgreSQL作为数据库,需要创建一个事件并保存事件的详细信息以及事件传单。我将事件传单作为multipartFile
传递给eventController
,在Service类中将其转换为字节数组使用getBytes()
方法。我已经按如下方式实现了代码,并尝试使用Postman发送请求。
这是我的Event实体:
package com.example.attendingsystembackend.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Lob;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.hibernate.annotations.GenericGenerator;
import java.time.LocalDateTime;
@Entity
public class Event {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
private String id;
@NotBlank(message = "Event name cannot be blank")
private String eventName;
private String eventType;
@NotBlank(message = "Event location cannot be blank")
private String location;
@NotNull
private LocalDateTime startTime;
@NotNull
private LocalDateTime endTime;
@Lob
private byte[] eventFlyer;
// ... Getters and setters
}
这是我的事件服务类:
package com.example.attendingsystembackend.service;
import com.example.attendingsystembackend.model.Event;
import com.example.attendingsystembackend.repository.EventRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Service
public class EventService {
private final EventRepository eventRepository;
@Autowired
public EventService(EventRepository eventRepository) {
this.eventRepository = eventRepository;
}
public void saveEvent(MultipartFile file, Event event) throws IOException {
Event newEvent = new Event();
// 设置事件属性...
if (file != null && !file.isEmpty()) {
byte[] fileBytes = file.getBytes();
newEvent.setEventFlyer(fileBytes);
} else {
newEvent.setEventFlyer(null);
}
eventRepository.save(newEvent);
}
}
这是我的事件控制器类:
package com.example.attendingsystembackend.controller;
import com.example.attendingsystembackend.model.Event;
import com.example.attendingsystembackend.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("api/event")
public class EventController {
private final EventService eventService;
@Autowired
public EventController(EventService eventService) {
this.eventService = eventService;
}
@PostMapping(value="saveEvent")
public ResponseEntity<String> saveEvent(@RequestParam(value = "file", required = false) MultipartFile file, Event event) {
try {
eventService.saveEvent(file, event);
return ResponseEntity.status(HttpStatus.OK)
.body(String.format("Event saved successfully with file: %s", file.getOriginalFilename()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(String.format("Could not save the event: %s!", e));
}
}
}
问题似乎出现在将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 :
`package com.example.attendingsystembackend.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Lob;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.hibernate.annotations.GenericGenerator;
import java.time.LocalDateTime;
@Entity
public class Event {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",strategy = "uuid")
private String id;
@NotBlank(message = "Event name cannot be blank")
private String eventName;
private String eventType;
@NotBlank(message = "Event location cannot be blank")
private String location;
@NotNull
private LocalDateTime startTime;
@NotNull
private LocalDateTime endTime;
@Lob
private byte[] eventFlyer;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public LocalDateTime getStartTime() {
return startTime;
}
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
public byte[] getEventFlyer() {
return eventFlyer;
}
public void setEventFlyer(byte[] eventFlyer) {
this.eventFlyer = eventFlyer;
}
}`
And this is my event service class:
package com.example.attendingsystembackend.service;
import com.example.attendingsystembackend.model.Event;
import com.example.attendingsystembackend.repository.EventRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Service
public class EventService {
private final EventRepository eventRepository;
@Autowired
public EventService(EventRepository eventRepository) {
this.eventRepository = eventRepository;
}
public void saveEvent(MultipartFile file, Event event) throws IOException {
Event newEvent=new Event();
newEvent.setEventName(event.getEventName());
newEvent.setEventType(event.getEventType());
newEvent.setLocation(event.getLocation());
newEvent.setStartTime(event.getStartTime());
newEvent.setEndTime(event.getEndTime());
if(file!=null && !file.isEmpty()) {
byte[] fileBytes = file.getBytes();
newEvent.setEventFlyer(fileBytes);
}else{
newEvent.setEventFlyer(null);
}
eventRepository.save(newEvent);
}
}
And here is my event controller class:
package com.example.attendingsystembackend.controller;
import com.example.attendingsystembackend.model.Event;
import com.example.attendingsystembackend.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("api/event")
public class EventController {
private final EventService eventService;
@Autowired
public EventController(EventService eventService) {
this.eventService = eventService;
}
@PostMapping(value="saveEvent")
public ResponseEntity<String> saveEvent(@RequestParam(value = "file", required = false) MultipartFile file, Event event) {
try {
eventService.saveEvent(file,event);
return ResponseEntity.status(HttpStatus.OK)
.body(String.format("Event saved succesfully with file: %s", file.getOriginalFilename()));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(String.format("Could not save the event: %s!", e));
}
}
}
And tried to send request using postman as follows:
But Unfortunately I'm getting the following error:
Validation failed for argument [1] in public org.springframework.http.ResponseEntity<java.lang.String> com.example.attendingsystembackend.controller.EventController.saveEvent(org.springframework.web.multipart.MultipartFile,com.example.attendingsystembackend.model.Event): [Field error in object 'event' on field 'eventFlyer': 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 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte[]' for property 'eventFlyer'; Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte' for property 'eventFlyer[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile']] ]
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参数。而不是这样做:
@PostMapping(value="saveEvent")
public ResponseEntity<String> saveEvent(@RequestPart("file") MultipartFile file, @RequestPart("body") Event event) // 也可以将JSON作为字符串值传递,然后映射为对象
2). 您从Postman发送请求应该像这样(示例):
英文:
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
@PostMapping(value="saveEvent")
public ResponseEntity<String> saveEvent(@RequestPart("file") MultipartFile file, @RequestPart("body") 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论