将图像保存到grails中的web-app下的文件夹中

时间:2013-07-24 08:57:35

标签: 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()
}

3 个答案:

答案 0 :(得分:4)

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

步骤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>

Step2:然后在你的控制器的savePicture动作中:

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
        }

Step3:并在文件上传服务中(在这种情况下名为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
        }
    }

答案 1 :(得分:2)

您只需将MutipartFile复制到web-app文件夹即可。这是如何:

MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("myfile");
String fileName = System.currentTimeMillis() + f.name
String destinationFileName = configService.getAbsoluteDocumentsPath() + fileName // We will put it on web-app/documents/xxxxx
f.renameTo(new File(destinationFileName))
//Save filename to database in 
user.avatar = fileName
user.save()

在configService中我有(用于计算路径)

class ConfigService {
def grailsApplication

     /**
     * @return absolute path of documents
     */
    def getAbsoluteDocumentsPath(){
        def asolutePath = grailsApplication.mainContext.servletContext.getRealPath('documents')
        return asolutePath.endsWith("/") ? asolutePath : asolutePath + "/"
    }
}

修改 确保您的请求是MutipartHttServletRequest的实例添加以下测试

if(request instanceof MultipartHttpServletRequest) {
//Do stuff here
}

不要忘记检查输入文件的表单的编码。

答案 2 :(得分:0)

我很容易解决这个问题,如下所示。您必须输入以下内容:

import org.apache.commons.io.FileUtils

import org.springframework.web.multipart.commons.CommonsMultipartFile

import org.springframework.web.multipart。*

祝你好运谁需要这个&gt;&gt;&gt;

def saveImageToFolder = {
    String message = ""
    MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
    CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("userPhoto")

    if(!f.empty) {
        def usr = User.findByUsername(1)
        if(!usr){
        User user = new User()
        user.username = params.username
        user.avatarType = f.getContentType()

        if(user.save()){
            def userId = user.id
            String username = user.username
            String fileName = username + "." + f.getContentType().substring(6)          // here my file type is image/jpeg
            byte[] userImage = f.getBytes()
            FileUtils.writeByteArrayToFile(new File( grailsApplication.config.images.location.toString() + File.separatorChar + fileName ), userImage )
            message = "User Created Successfully."
        }else{
            message = "Can not Create User !!!"
        }
        }else{
            message = "Username already exists. Please try another one !!!"
        }
    }
    else {
        message = 'file cannot be empty'
    }
    render(view: 'addUser', model:[message: message])
}

并在配置文件中粘贴此&gt;&gt;&gt;

images.location = "web-app/images/userImages/"      // after web-app/folder name/folder name and go on if you want to add other folder