¾«Í¨ Grails: ÎļþÉÏ´«ºÍ Atom ÁªºÏ(2)

À´Ô´:developerWorks Öйú ×÷Õß:Scott Davis
¡¡¡¡

×¢Ò⣬ÕâÀïʹÓà request.getFile() ·½·¨»ñµÃÉÏ´«µÄÎļþµÄÒýÓá£ÓÐÁ˸ÃÒýÓú󣬱ã¿ÉÒÔ¶ÔËü½øÐи÷ÖÖÀàÐ͵ÄÄÚÊ¡¡£Çåµ¥ 7 ÏÔʾÉÏ´« Grails »Õ±êºóµÄ¿ØÖÆ̨Êä³ö£º


Çåµ¥ 7. ÉÏ´«ÎļþºóµÄ¿ØÖÆ̨Êä³ö
				
Class: class org.springframework.web.multipart.commons.CommonsMultipartFile
Name: payload
OriginalFileName: Grails_logo.jpg
Size: 8065
ContentType: image/jpeg

Èç¹ûÖªµÀ Grails ÔÚÄ»ºóʹÓà Spring MVC ¿ò¼Ü£¬ÄÇô¶Ô´Ë²»Ó¦¸Ðµ½Ææ¹Ö£ºÉÏ´«µÄÎļþÊÇ×÷Ϊ CommonsMultipartFile ¶ÔÏóÌṩ¸ø¿ØÖÆÆ÷µÄ¡£³ýÁ˹«²¼ HTML ±íµ¥×ֶεÄÃû³ÆÍ⣬Õâ¸öÀ໹ÔÊÐí·ÃÎÊԭʼÎļþÃû¡¢Îļþ´óС£¨µ¥Î»Îª×Ö½Ú£©ºÍÎļþµÄ MIME ÀàÐÍ¡£

½ÓÏÂÀ´µÄ²½ÖèÊǽ«ÉÏ´«µÄÎļþ±£´æµ½Ä³¸öµØ·½¡£ÔÚ save ±Õ°üÖÐÌí¼Ó¼¸ÐдúÂ룬ÈçÇåµ¥ 8 Ëùʾ£º


Çåµ¥ 8. ½«ÉÏ´«µÄÎļþ±£´æµ½´ÅÅÌ
				
def save = {
    def entryInstance = new Entry(params)
    entryInstance.author = User.get(session.user.id)

    //handle uploaded file
    def uploadedFile = request.getFile('payload')
    if(!uploadedFile.empty){
      println "Class: ${uploadedFile.class}"
      println "Name: ${uploadedFile.name}"
      println "OriginalFileName: ${uploadedFile.originalFilename}"
      println "Size: ${uploadedFile.size}"
      println "ContentType: ${uploadedFile.contentType}"

      def webRootDir = servletContext.getRealPath("/")
      def userDir = new File(webRootDir, "/payload/${session.user.login}")
      userDir.mkdirs()
      uploadedFile.transferTo( new File( userDir, uploadedFile.originalFilename))
    }

    if(!entryInstance.hasErrors() && entryInstance.save()) {
        flash.message = "Entry ${entryInstance.id} created"
        redirect(action:show,id:entryInstance.id)
    }
    else {
        render(view:'create',model:[entryInstance:entryInstance])
    }
}

ÔÚ Web root Ï´´½¨ payload/jsmith Ŀ¼ºó£¬¾Í¿ÉÒÔʹÓà uploadedFile.transferTo() ·½·¨½«Îļþ±£´æµ½´ÅÅÌ¡£File.mkdirs() ·½·¨ÊÇÎÞËðµÄ£¬ËùÒÔ¿ÉÒÔ¶à´Îµ÷Óø÷½·¨£¬¶ø²»±Øµ£Ðĵ±Ä¿Â¼ÒѾ­´æÔÚʱ»á¶ªÊ§ÒÑÓеÄÎļþ¡£

½ÓÏÂÀ´£¬½«Ò»¸ö String ×Ö¶ÎÌí¼Óµ½ Entry À࣬ÒÔ´æ´¢ filename£¬ÈçÇåµ¥ 9 Ëùʾ¡£×¢ÒâÒªÌí¼ÓÒ»¸öÔ¼Êø£¬Ê¹Õâ¸öÐÂ×Ö¶ÎͬʱΪ blank£¨ÔÚ HTML ±íµ¥ÖУ©ºÍ nullable£¨ÔÚÊý¾Ý¿âÖУ©¡£


Çåµ¥ 9. ½« filename ×Ö¶ÎÌí¼Óµ½ Entry ÖÐ
				
class Entry {
  static constraints = {
    title()
    summary(maxSize:1000)
    filename(blank:true, nullable:true)
    dateCreated()
    lastUpdated()
  }

  static mapping = {
    sort "lastUpdated":"desc"
  }

  static belongsTo = [author:User]

  String title
  String summary
  String filename
  Date dateCreated
  Date lastUpdated
}

×îºó£¬½« filename Ìí¼Óµ½ save ±Õ°üÖÐµÄ Entry ¶ÔÏóÖС£Çåµ¥ 10 ÏÔʾÍêÕûµÄ save ±Õ°ü£º


Çåµ¥ 10. ½« filename ´æ´¢ÔÚ Entry ÖÐ
				
def save = {
    def entryInstance = new Entry(params)
    entryInstance.author = User.get(session.user.id)

    //handle uploaded file
    def uploadedFile = request.getFile('payload')
    if(!uploadedFile.empty){
      println "Class: ${uploadedFile.class}"
      println "Name: ${uploadedFile.name}"
      println "OriginalFileName: ${uploadedFile.originalFilename}"
      println "Size: ${uploadedFile.size}"
      println "ContentType: ${uploadedFile.contentType}"

      def webRootDir = servletContext.getRealPath("/")
      def userDir = new File(webRootDir, "/payload/${session.user.login}")
      userDir.mkdirs()
      uploadedFile.transferTo( new File( userDir, uploadedFile.originalFilename))
      entryInstance.filename = uploadedFile.originalFilename
    }

    if(!entryInstance.hasErrors() && entryInstance.save()) {
        flash.message = "Entry ${entryInstance.id} created"
        redirect(action:show,id:entryInstance.id)
    }
    else {
        render(view:'create',model:[entryInstance:entryInstance])
    }
}

½«ÉÏ´«µÄÎļþ±£´æµ½ÎļþϵͳµÄÁíÒ»ÖÖ·½·¨Êǽ«ËüÃÇÖ±½Ó´æ´¢ÔÚÊý¾Ý¿âÖС£Èç¹ûÔÚ Entry Öд´½¨Ò»¸öÃûΪ payload µÄ byte[] ×ֶΣ¬ÄÇô¿ÉÒÔÍêÈ«ÈƹýÇ°ÃæÌí¼Óµ½ save ±Õ°üµÄËùÓж¨ÖÆ´úÂë¡£µ«ÊÇ£¬Èç¹ûÄÇÑù×öµÄ»°£¬Äú½«´í¹ýÏÂÒ»½ÚÖÐËùÓеÄȤÊ¡£





ÏÔʾÉÏ´«µÄÎļþ

Èç¹û²»½«ÉÏ´«µÄÎļþÔÚij¸öµØ·½ÏÔʾ³öÀ´£¬ÄÇÓкÎÒâÒåÄØ£¿´ò¿ª grails-app/views/entry/_entry.gsp£¬Ìí¼ÓÇåµ¥ 11 ÖеĴúÂ룺


Çåµ¥ 11. ÓÃÓÚÏÔʾÉÏ´«µÄͼÏñµÄ GSP ´úÂë
				
<div class="entry">
  <span class="entry-date">
      <g:longDate>${entryInstance.lastUpdated}</g:longDate> : ${entryInstance.author}
  </span>
  <h2><g:link action="show" id="${entryInstance.id}">${entryInstance.title}</g:link></h2>
  <p>${entryInstance.summary}</p>

  <g:if test="${entryInstance.filename}">
    <p>
      <img src="${createLinkTo(dir:'payload/'+entryInstance.author.login,
                               file:''+entryInstance.filename)}"
           alt="${entryInstance.filename}"
           title="${entryInstance.filename}" />
    </p>
  </g:if>
</div>

ÓÉÓÚÉÏ´«ÎļþÊÇ¿ÉÑ¡µÄ£¬ÎÒ½«Êä³ö°üº¬ÔÚÒ»¸ö <g:if> ¿éÖС£Èç¹û entryInstance.filename ×ֶα»Ìî³ä£¬ÔòÔÚÒ»¸ö <img> ±ê¼ÇÖÐÏÔʾ½á¹û¡£

ͼ 2 ÏÔʾеÄÁÐ±í£¬Í¬Ê±»¹ÔÚÏÔÑ۵ĵط½ÏÔʾÉÏ´«µÄ Grails »Õ±ê£º


ͼ 2. ÏÔʾÉÏ´«µÄͼÏñ

µ«ÊÇ£¬Èç¹ûÓû§ÉÏ´«ÆäËû¶«Î÷£¬¶ø²»ÊÇͼÏñÄØ£¿Õâʱ¾Í²»Êǽ«¸ü¶àµÄÂß¼­·ÅÈëµ½ GSP ÖÐÁË£¬×îºÃµÄµØ·½ÊÇÒ»¸ö¶¨ÖÆµÄ TagLib¡£





´´½¨ TagLib

Blogito ÔÚ grails-app/taglib ÖÐÒѾ­ÓÐÁ½¸ö TagLib£ºDateTagLib.groovy ºÍ LoginTagLib.groovy¡£ÔÚÒ»¸ö TagLib ÖпÉÒÔ¶¨ÒåÈÎÒâÊýÁ¿µÄ¶¨ÖƱê¼Ç£¬µ«ÊÇÕâÒ»´ÎÎÒ½¨Òé´´½¨Ò»¸öÐ嵀 TagLib£¬ÒԱ㰴ÓïÒ彫±ê¼Ç·Ö×é¡£ÔÚÃüÁîÌáʾ·ûÏÂÊäÈë grails create-tag-lib Entry£¬²¢Ìí¼ÓÇåµ¥ 12 ÖеĴúÂ룺


Çåµ¥ 12. ´´½¨ displayFile ±ê¼Ç
				
class EntryTagLib {

  def displayFile = {attrs, body->
    def user = attrs["user"]
    def filename = attrs["filename"]

    if(filename){
      def extension = filename.split("\\.")[-1]
      def userDir = "payload/${user}"

      switch(extension.toUpperCase()){
        case ["JPG", "PNG", "GIF"]:
             def html = """
             <p>
               <img src="${createLinkTo(dir:''+userDir,
                                        file:''+filename)}"
                    alt="${filename}"
                    title="${filename}" />
             </p>
             """

             out << html
             break

        case "HTML":
             out << "p>html</p>"
             break
        default:
             out << "<p>file</p>"
             break
      }
    }else{
      out << "<!-- no file -->"
    }
  }

}

²»¾Ãºó¿ÉÒÔ¿´µ½£¬¸Ã´úÂë´´½¨Ò»¸ö <g:displayFile> ±ê¼Ç£¬¸Ã±ê¼ÇÐèÒªÁ½¸öÊôÐÔ£ºuser ºÍ filename¡£Èç¹û filename ÊôÐÔ±»Ìî³ä£¬ÔòÈ¡µÃÎļþÀ©Õ¹Ãû£¬²¢½«Æäת»»Îª´óдÐÎʽ¡£

Groovy ÖÐµÄ Switch Óï¾ä±È Java ÖеĶԵÈÎïµÄÁé»îÐÔÒª´óµÃ¶à¡£Ê×ÏÈ£¬¿ÉÒÔÔÚ String ÉϽøÐÐÇл»£¨¶ø Java ÓïÑÔÖ»ÄÜÔÚ int ÉϽøÐÐÇл»£©¡£¸üÁîÈ˾ªÆæµÄÊÇ£¬case ¼È¿ÉÒÔÖ¸¶¨Ò»¸öÌõ¼þÁбí List£¬Ò²¿ÉÒÔÖ¸¶¨µ¥¸öµÄÌõ¼þ¡£

ÓÐÁËÕâ¸ö TagLib ºó£¬¿ÉÒÔ´ó´ó¼ò»¯ _entry.gsp ¾Ö²¿Ä£°å£¬ÈçÇåµ¥ 13 Ëùʾ£º


ʱ¼ä:2009-07-06 17:18 À´Ô´:developerWorks Öйú ×÷Õß:Scott Davis Ô­ÎÄÁ´½Ó

ºÃÎÄ,¶¥Ò»ÏÂ
(3)
100%
ÎÄÕÂÕæ²î,²ÈÒ»ÏÂ
(0)
0%
------·Ö¸ôÏß----------------------------


°Ñ¿ªÔ´´øÔÚÄãµÄÉí±ß-¾«ÃÀlinuxС¼ÍÄîÆ·
ÎÞÃÙÏà¹ØÎÄÕ²å¼þ£¬¿ìËÙÌáÉýÁ÷Á¿