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

问题描述 投票:0回答:1

我正在做一个 spring boot 项目,我使用 postgresql 作为我的数据库。在我的项目中,我需要创建一个活动并保存活动的详细信息以及活动传单。我将事件传单作为 multipartFile 传递给 eventController,在服务类中,我将使用方法

getBytes()
将其转换为字节数组。我实现了如下代码,并尝试使用邮递员发送请求。

这是我的事件实体:

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

并尝试使用邮递员发送请求如下:

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

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

因为我觉得将

MultiPartFile
转换为
byte[] 
时发生了错误,有人可以帮我解决这个问题吗?我在这里犯了什么错误?提前谢谢你。

java spring-boot post request
1个回答
1
投票

我在这里注意到两件事,

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).你对邮递员的要求应该是这样的。(样本)

© www.soinside.com 2019 - 2024. All rights reserved.