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

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

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 = &quot;system-uuid&quot;)
    @GenericGenerator(name=&quot;system-uuid&quot;,strategy = &quot;uuid&quot;)
    private String id;

    @NotBlank(message = &quot;Event name cannot be blank&quot;)
    private String eventName;

    private String eventType;

    @NotBlank(message = &quot;Event location cannot be blank&quot;)
    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 &amp;&amp; !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(&quot;api/event&quot;)
public class EventController {

    private final EventService eventService;

    @Autowired
    public EventController(EventService eventService) {
        this.eventService = eventService;
    }

    @PostMapping(value=&quot;saveEvent&quot;)
    public ResponseEntity&lt;String&gt; saveEvent(@RequestParam(value = &quot;file&quot;, required = false) MultipartFile file, Event event) {
        try {
            eventService.saveEvent(file,event);

            return ResponseEntity.status(HttpStatus.OK)
                    .body(String.format(&quot;Event saved succesfully with file: %s&quot;, file.getOriginalFilename()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(String.format(&quot;Could not save the event: %s!&quot;, e));
        }
    }
}

And tried to send request using postman as follows:

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

But Unfortunately I'm getting the following error:

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参数。而不是这样做:

@PostMapping(value="saveEvent")
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

@PostMapping(value=&quot;saveEvent&quot;)
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:

确定