File
Entity
package software.mama.furniture.vo.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
import javax.persistence.*;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
@Entity
@Data
@NoArgsConstructor
public class File {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Lob
private byte[] bytes;
@Column(name = "mimetype")
private String mimeType;
private String name;
private Long size;
@Enumerated(EnumType.STRING)
private Kind kind;
private Long seq;
private LocalDateTime timelog;
@Column(name = "articleid")
private Long articleId;
public File(MultipartFile attachment) throws IOException {
bytes = attachment.getBytes();
mimeType = attachment.getContentType();
name = attachment.getOriginalFilename();
size = attachment.getSize();
}
public enum Kind {
THUMBNAIL, CAROUSEL
}
}
image를 payload 로 넘기기
package software.mama.furniture.controller;
import javassist.tools.web.BadHttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import software.mama.furniture.repository.FileRepository;
@Controller
@RequestMapping("/files")
public class FileController {
@Autowired
private FileRepository fileRepository;
@GetMapping("/{id}")
public ResponseEntity<byte[]> file(@PathVariable Long id) throws BadHttpRequest {
return fileRepository.findById(id).map(self -> ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + self.getName() + "\"")
.contentType(MediaType.parseMediaType(self.getMimeType()))
.body(self.getBytes())
).orElseThrow(()-> new BadHttpRequest(new Exception("해당 id("+id+")를 가진 데이터가 없습니다.")));
}
}