Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ import com.wafflestudio.csereal.core.resource.attachment.database.AttachmentEnti

interface AttachmentAttachable {
val attachments: List<AttachmentEntity>

fun getAttachmentFolder(): String
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ package com.wafflestudio.csereal.common.entity
import com.wafflestudio.csereal.core.resource.mainImage.database.MainImageEntity

interface MainImageAttachable {
val mainImage: MainImageEntity?
var mainImage: MainImageEntity?

fun getMainImageFolder(): String
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[마이너] getter 보다는 다른 네이밍으로 수정되면 더 좋을 거 같습니다..! (실제 field는 아니니까요..?)

}
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,8 @@ class AboutEntity(
assert(postType == AboutPostType.FUTURE_CAREERS)
searchContent = createContent(name, description, statNames, companyNames)
}

override fun getAttachmentFolder() = "attachment/about"

override fun getMainImageFolder() = "mainImage/about"
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,6 @@ class AcademicsEntity(
)
}
}

override fun getAttachmentFolder() = "attachment/academics"
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ class CouncilEntity(
name = req.name
)
}

override fun getMainImageFolder() = "mainImage/council"
}

enum class CouncilType {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ class CouncilFileEntity(

@OneToMany(mappedBy = "councilFile", cascade = [CascadeType.ALL], orphanRemoval = true)
override val attachments: MutableList<AttachmentEntity> = mutableListOf()
) : BaseTimeEntity(), AttachmentAttachable
) : BaseTimeEntity(), AttachmentAttachable {
override fun getAttachmentFolder() = "attachment/council"
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ class ProfessorEntity(
this.lab = lab
lab.professors.add(this)
}

override fun getMainImageFolder() = "mainImage/professor"
}

enum class ProfessorStatus(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,6 @@ class StaffEntity(
this.phone = staffDto.phone
this.email = staffDto.email
}

override fun getMainImageFolder() = "mainImage/staff"
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,8 @@ class NewsEntity(
this.isImportant = updateNewsRequest.isImportant
this.importantUntil = if (updateNewsRequest.isImportant) updateNewsRequest.importantUntil else null
}

override fun getAttachmentFolder() = "attachment/news"

override fun getMainImageFolder() = "mainImage/news"
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,6 @@ class NoticeEntity(
this.isImportant = updateNoticeRequest.isImportant
this.importantUntil = if (updateNoticeRequest.isImportant) updateNoticeRequest.importantUntil else null
}

override fun getAttachmentFolder() = "attachment/notice"
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ class RecruitEntity(

@OneToOne
override var mainImage: MainImageEntity? = null
) : BaseTimeEntity(), MainImageAttachable
) : BaseTimeEntity(), MainImageAttachable {
override fun getMainImageFolder() = "mainImage/research"
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,6 @@ class ResearchEntity(
)
}
}

override fun getMainImageFolder() = "mainImage/research"
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class AttachmentEntity(
@Column(unique = true)
val filename: String,

val folder: String? = null,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이렇게 수정되면 <folder, filename> -> unique로 수정되는게 맞겠네요..!


val attachmentsOrder: Int,
val size: Long,

Expand Down Expand Up @@ -57,4 +59,8 @@ class AttachmentEntity(
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "council_file_id")
var councilFile: CouncilFileEntity? = null
) : BaseTimeEntity()
) : BaseTimeEntity() {
fun filePath(): String {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이건 수정해주세요보다는 방향성을 고민해보면 좋을 거 같아서 코멘트 남깁니다.
현재 각 entity에서 구현한 attachable 인터페이스는 결국 패턴이 "{attachment,mainImage}/{domain}"의 형태로 고정되는거 같고,
각 도메인의 entity가 '어떤 경로에 저장되어야 한다'라는 정보까지 들고 있을 필요가 있을지는 고민되요.

위에 문제를 벗어나기 위해서 각 entity에 method를 정의한다기보다는
(fileType, attachable) -> String 의 식으로 resource/common 패키지 하위에 method를 추가하는 것도 한가지 방법일 거 같아요.

다만 어떻게 하든 장단점은 있어보이네요..!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

원래 attachable -> String 형식으로 메소드를 AttachmentService에 만들었는데, 저장 위치는 attachable이라면 가져야 할 속성이라 생각해 이렇게 수정했습니다.
다시 생각해보니 저장 위치를 하나의 함수에서 관리해줘야 한눈에 보기 편할 것 같기도 합니다.
수정해보겠습니다.

return if (folder.isNullOrBlank()) return filename else "$folder/$filename"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.multipart.MultipartFile
import java.lang.invoke.WrongMethodTypeException
import java.nio.file.Files
import java.nio.file.Paths

Expand Down Expand Up @@ -53,22 +54,25 @@ class AttachmentServiceImpl(
private val eventPublisher: ApplicationEventPublisher
) : AttachmentService {
override fun uploadAttachmentInLabEntity(labEntity: LabEntity, requestAttachment: MultipartFile): AttachmentDto {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

흠 얘도 추후에 추상화가 되면 좋겠군요..

Files.createDirectories(Paths.get(path))
val folder = "attachment/lab"
val uploadDir = Paths.get(path, folder)
Files.createDirectories(uploadDir)

val timeMillis = System.currentTimeMillis()

val filename = "${timeMillis}_${requestAttachment.originalFilename}"
val totalFilename = path + filename
val saveFile = Paths.get(totalFilename)
val saveFile = Paths.get(path, folder, filename)
requestAttachment.transferTo(saveFile)

val attachment = AttachmentEntity(
filename = filename,
folder = folder,
attachmentsOrder = 1,
size = requestAttachment.size
)

labEntity.pdf = attachment
attachment.lab = labEntity
attachmentRepository.save(attachment)

return AttachmentDto(
Expand All @@ -83,20 +87,22 @@ class AttachmentServiceImpl(
contentEntityType: AttachmentAttachable,
requestAttachments: List<MultipartFile>
): List<AttachmentDto> {
Files.createDirectories(Paths.get(path))
val folder = contentEntityType.getAttachmentFolder()
val uploadDir = Paths.get(path, folder)
Files.createDirectories(uploadDir)

val attachmentsList = mutableListOf<AttachmentDto>()

for ((index, requestAttachment) in requestAttachments.withIndex()) {
val timeMillis = System.currentTimeMillis()

val filename = "${timeMillis}_${requestAttachment.originalFilename}"
val totalFilename = path + filename
val saveFile = Paths.get(totalFilename)
val saveFile = uploadDir.resolve(filename)
requestAttachment.transferTo(saveFile)

val attachment = AttachmentEntity(
filename = filename,
folder = folder,
attachmentsOrder = index + 1,
size = requestAttachment.size
)
Expand Down Expand Up @@ -124,7 +130,7 @@ class AttachmentServiceImpl(
attachmentDto = AttachmentResponse(
id = attachment.id,
name = attachment.filename.substringAfter("_"),
url = "${endpointProperties.backend}/v1/file/${attachment.filename}",
url = "${endpointProperties.backend}/v1/file/${attachment.filePath()}",
bytes = attachment.size
)
}
Expand All @@ -142,7 +148,7 @@ class AttachmentServiceImpl(
val attachmentDto = AttachmentResponse(
id = attachment.id,
name = attachment.filename.substringAfter("_"),
url = "${endpointProperties.backend}/v1/file/${attachment.filename}",
url = "${endpointProperties.backend}/v1/file/${attachment.filePath()}",
bytes = attachment.size
)
list.add(attachmentDto)
Expand Down Expand Up @@ -170,7 +176,7 @@ class AttachmentServiceImpl(

@Transactional
override fun deleteAttachment(attachment: AttachmentEntity) {
val fileDirectory = path + attachment.filename
val fileDirectory = path + attachment.filePath()
attachmentRepository.delete(attachment)
eventPublisher.publishEvent(FileDeleteEvent(fileDirectory))
}
Expand Down Expand Up @@ -217,6 +223,10 @@ class AttachmentServiceImpl(
contentEntity.attachments.add(attachment)
attachment.councilFile = contentEntity
}

else -> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 메서드도 main image처럼 추후 간단하게 할 수 있다면 좋겠네용...

throw WrongMethodTypeException("파일을 엔티티에 연결할 수 없습니다")
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@ class FileController(
private val uploadPath: String,
private val endpointProperties: EndpointProperties
) {

@GetMapping("/{filename:.+}")
@GetMapping("/{*filepath}")
fun serveFile(
@PathVariable filename: String,
@PathVariable filepath: String,
request: HttpServletRequest
): ResponseEntity<Resource> {
val file = Paths.get(uploadPath, filename)
val file = Paths.get(uploadPath, filepath)
val resource = UrlResource(file.toUri())

if (resource.exists() || resource.isReadable) {
Expand All @@ -41,6 +40,7 @@ class FileController(

headers.contentType = MediaType.parseMediaType(contentType ?: "application/octet-stream")

val filename = filepath.substringAfterLast("/")
val originalFilename = filename.substringAfter("_")
val encodedFilename = URLEncoder.encode(originalFilename, UTF_8.toString()).replace("+", "%20")

Expand Down Expand Up @@ -69,7 +69,7 @@ class FileController(
val saveFile = Paths.get(totalFilename)
file.transferTo(saveFile)

val imageUrl = "${endpointProperties.backend}/v1/file/$filename"
val imageUrl = "/v1/file/$filename"

results.add(
UploadFileInfo(
Expand All @@ -93,9 +93,12 @@ class FileController(
}

@PreAuthorize("hasRole('STAFF')")
@DeleteMapping("/{filename:.+}")
fun deleteFile(@PathVariable filename: String): ResponseEntity<Any> {
val file = Paths.get(uploadPath, filename)
@DeleteMapping("/{*filepath}")
fun deleteFile(
@PathVariable filepath: String,
request: HttpServletRequest
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

request 추가한 이유가 있을까요? 보기에는 필요 없어 보여서요..!

): ResponseEntity<Any> {
val file = Paths.get(uploadPath, filepath)

if (Files.exists(file)) {
Files.delete(file)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ class MainImageEntity(
@Column(unique = true)
val filename: String,

val folder: String? = null,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[마이너] folder -> directory 등으로 이름 변경하는 것도 괜찮을거 같습니다..! (folder는 주로 윈도우에서만 쓰는 느낌이라서..?)


val imagesOrder: Int,
val size: Long

) : BaseTimeEntity()
) : BaseTimeEntity() {
fun filePath(): String {
return if (folder.isNullOrBlank()) return filename else "$folder/$filename"
}
}
Loading
Loading