image - 在grails中将图像保存到Web应用程序下的文件夹

标签 image grails grails-2.0

我需要将图像保存到应用程序中的文件夹中。到目前为止,我已经学会了将图像保存到数据库中,但是我需要将其保存到文件夹中。我怎样才能做到这一点?谁能帮我这个忙吗?这是我下面的代码,保存到数据库中>>>

def upload={
  def user = User.findById(1)
    CommonsMultipartFile file = params.list("photo")?.getAt(0)
    user.avatar = file?.bytes
    user.save()
}

最佳答案

在下面查找逐步实现的方法,我添加了一个带有uploadForm的GSP页面(默认情况下将进行多部分表单提交),然后是一个 Controller 函数来处理文件保存请求,以及一种将文件保存到指定目录中的服务方法:

步骤1:建立文件上载表格:

<g:uploadForm name="picUploadForm" class="well form-horizontal" controller="<your-controller-name>" action="savePicture">

    Select Picture: <input type="file" name="productPic"/>
    <button type="submit" class="btn btn-success"><g:message code="shopItem.btn.saveProductImage" default="Save Image" /></button>



</g:uploadForm>

步骤2:然后在 Controller 的savePicture Action 中:
String baseImageName = java.util.UUID.randomUUID().toString();
// Saving image in a folder assets/channelImage/, in the web-app, with the name: baseImageName
        def downloadedFile = request.getFile( "product.baseImage" )
        String fileUploaded = fileUploadService.uploadFile( downloadedFile, "${baseImageName}.jpg", "assets/channelImage/" )
        if( fileUploaded ){
            // DO further actions, for example make a db entry for the file name
        }

步骤3:并在文件上传器服务中(在这种情况下,用户定义的服务名为FileUploadService):
def String uploadFile( MultipartFile file, String name, String destinationDirectory ) {

        def serveletContext = ServletContextHolder.servletContext
        def storagePath = serveletContext.getRealPath( destinationDirectory )

        def storagePathDirectory = new File( storagePath )

        if( !storagePathDirectory.exists() ){
            println("creating directory ${storagePath}")
            if(storagePathDirectory.mkdirs()){
                println "SUCCESS"
            }else{
                println "FAILED"
            }
        }

        // Store file

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

关于image - 在grails中将图像保存到Web应用程序下的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17829413/

相关文章:

tomcat - JNDI Tomcat Servelet(grails)尝试从身份验证的 LDAP 绑定(bind)中获取更多属性

grails - Grails插件站点版本语法

arrays - 您可以为 C 中的二维数组的 struct 中的所有元素赋值吗?

html - 将 2x2 图像裁剪并叠加到 4x4 网格上,不重复列/行

python - 如何使用 OpenCV 读取图像目录

java - -> 运算符在 grails 中的含义和用法是什么?

grails - Groovy:使用Grails和Spring安全核心插件时出现意外 token

c# - ASP.NET MVC 2 不显示 CSS 文件中的图像

grails - 在Grails Spring Security Core插件中设置 session 超时

grails - log4j:参数附加程序文件名