【问题标题】:upload image to web-app/image directory in grails将图像上传到 grails 中的 web-app/image 目录
【发布时间】:2016-01-03 16:17:16
【问题描述】:

我正在尝试构建一个具有图像上传功能的应用程序...问题是我找不到将图像上传到 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

【问题讨论】:

    标签: image grails upload


    【解决方案1】:

    首先,您不应该将图像上传到应用程序的目录,因为如果您使用版本控制 (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 目录的路径。

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 2015-03-18
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多