2017-06-18 21 views

回答

0

視圖代碼

<g:form controller="yourController" action="yourAction" class="form-horizontal" enctype="multipart/form-data"> 
First name: <input type="text" name="fname"><br> 
    Last name: <input type="text" name="lname"><br> 
    Your image: <input type="file" name="pic" id="pic"><br> 
    <input type="submit" value="Submit"> 
</g:form> 

控制器代碼

def save_listing(){ 

     String storagePath = "" 
     Environment.executeForCurrentEnvironment { 
      development { 
       //def servletContext = ServletContextHolder.servletContext 
       storagePath = "/your/path/to store/locally" 
      } 
      production { 
       storagePath = "/opt/home/images" 
      } 
     } 

     List<MultipartFile> files = request.multiFileMap.pic 
     int count = files.findAll { !it.empty }.size 
     for (int i = 0; i <files.size(); i++) { 
      fileUploadService.uploadFile(files[i], "${i}.jpg", "${storagePath}/${Listing.findAll().size()+1}") 
     } 

     render("success") 


    } 

服務代碼

def String uploadFile(MultipartFile file, String name, String destinationDirectory) { 

    def storagePathDirectory = new File(destinationDirectory) 
    if (!storagePathDirectory.exists()) { 
     print "CREATING DIRECTORY ${destinationDirectory}: " 
     if (storagePathDirectory.mkdirs()) { 
      println "SUCCESS" 
     } else { 
      println "FAILED" 
     } 
    } 

    if (!file.isEmpty()) { 
     file.transferTo(new File("${destinationDirectory}/${name}")) 
     println "Saved file: ${destinationDirectory}/${name}" 
     return "${destinationDirectory}/${name}" 
    } else { 
     println "File ${file.inspect()} was empty!" 
     return null 
    } 

} 

此解決方案將幫助您一次上傳多個圖像。良好的做法是將圖像上傳到目錄no db。

相關問題