将图片上传到 grails 中的 web-app/image 目录

upload image to web-app/image directory in grails

我正在尝试构建一个具有图像上传功能的应用程序...问题是我找不到将图像上传到 web-app/images 目录的方法..我正在使用 Grails 2.2.1 并且无法执行那..如果有人能帮忙就太好了..提前谢谢你们!!我尝试了一些代码并将其上传到控制器,但我找不到将其上传到目录的方法..我的控制器有以下代码:

def file = request.getFile('image')

def name = file.getOriginalFilename()
println "file is "+name
if (file && !file.empty) {
    //I dont know how to specify directory and upload the image file, the code must be written here
    flash.message = 'Image uploaded'
}ere

首先,你永远不应该将图像上传到你的应用程序目录,因为如果你使用版本控制 (git | svn),它会使应用程序变得更重,因为文件也受到版本控制。

您可以做的是将图像保存在其他位置并将位置路径保存在 Config.groovy

    imageUpload.path='your location'

并在需要时以

身份访问此位置
    grailsApplication.config.imageUpload.path

现在使用 <g:uploadForm> 标签创建一个表单,或者您可以使用普通的 <form> 标签,但请确保将 enctype 属性更改为 multipart/form-data

查看演示表格

    <g:uploadForm action="uploadImage">
        <input type="file" name="image">
        <input type="submit" value="Upload Image">
    </g:uploadForm>

现在在您的控制器中您可以执行操作 uploadImage

    def uploadImage(){
      def file=request.getFile('image')
      String imageUploadPath=grailsApplication.config.imageUpload.path
      try{
         if(file && !file.empty){
         file.transferTo(new File("${imageUploadPath}/${file.name}"))
         flash.message="your.sucessful.file.upload.message"
         }
         else{
         flash.message="your.unsucessful.file.upload.message"
         }
      }
      catch(Exception e){
         log.error("Your exception message goes here",e)   
      }

    }

这将有助于上传您的图片,但不会在您的 web-app/images 目录中。

但如果您仍想将其传输到您的 web-app/images 目录,您可以如上所述在 Config.groovy 中设置 web-app/images 目录的路径。