如何在spring Boot 中将MultipartFile转换为字节数组

roejwanj  于 2023-04-11  发布在  Spring
关注(0)|答案(1)|浏览(348)

我正在做一个spring Boot 项目,我使用postgresql作为我的数据库。在我的项目中,我需要创建一个事件,并将事件的详细信息与事件传单一起保存。我将事件传单作为multipartFile传递给eventController,并在Service类中使用方法getBytes()将其转换为字节数组。我实现了如下代码,并尝试使用postman发送请求。
这是我的事件实体:

`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;
    }
}`

这是我的事件服务类:

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);
    }

    }

下面是我的事件控制器类:

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));
        }
    }
}

并尝试使用 Postman 发送请求,如下所示:

但不幸的是,我得到以下错误:

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']] ]

因为我觉得错误发生时转换MultiPartFilebyte[]有人可以帮助我这个问题吗?我在这里做了什么错误?提前谢谢你.

cotxawn7

cotxawn71#

我注意到两件事,
1).在你的post方法中,你已经发送了一个多部分的文件和事件类,但是你把它们作为@Request参数发送。

@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).你的要求从 Postman 应该是这样的。(示例)

相关问题