- [Grails] 파일 업로드 - 여러 개의 파일을 첨부(데이터베이스에 저장)
- 日常茶飯事
- 2014. 2. 10. 02:00
class Attachment { String fileName Long fileSize byte[] file //업로드후 필요할때만 가지고 오도록 고려해야 함. String fileContentType String toString(){ fileName } }
class Article { List attachments static hasMany = [tags:Tag, comments:Comment, attachments:Attachment]
<g:form action="save" enctype="multipart/form-data"> - or - <g:uploadForm action="save">
<li><input type="file" name="attachments[0].file" /></li> <li><input type="file" name="attachments[1].file" /></li>
class ArticleController { def scaffold = Article def save() { def article = new Article(params) def emptyFiles = new ArrayList(); article.attachments.eachWithIndex{ attachment, i -> def file = request.getFile("attachments[$i].file") if(!file.empty){ //파일 바이너리는 이미 들어가 있음. attachment.fileName = file.originalFilename attachment.fileSize = file.size attachment.fileContentType = file.contentType }else{ emptyFiles << attachment } } article.attachments.removeAll(emptyFiles) //저장할 필요가 없는 데이터는 삭제한다. article.user = session.user // if (!article.save(flush: true)) {
Recent comment