删除grails中的现有文件

时间:2013-07-30 05:47:18

标签: grails file-upload file-io grails-2.0

我正在保存我的网络文件夹中的图像文件。但是在保存或假设用户想要更改他的图片时,我想要删除旧图片并使用相同的文件名保存新图片。但是我尝试后失败了。有人可以帮我这个吗?以下是我的所有行动:

我的保存操作>>>

    def savePicture = {
        String message = ""
        def user = User.findById(1)
        def userId = user.id
        MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
        CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("productPic");

        def okcontents = ['image/png', 'image/jpeg', 'image/gif']
        if (! okcontents.contains(f.getContentType())) {
            message = "Avatar must be one of: ${okcontents}"
            render(view:'uploadForm', model:[message: message])
            return;
        }

        String type = f.getContentType().substring(6)

        String baseImageName = java.util.UUID.randomUUID().toString();
        baseImageName = "user${user.id}"
// Saving image in a folder assets/channelImage/, in the web-app, with the name: baseImageName
        def downloadedFile = f  //.getFile( "product.baseImage" )
        String fileUploaded = fileUploadService.uploadFile( downloadedFile, "${baseImageName}.${type}", "assets/channelImage/" )
        if( fileUploaded ){
            user.avatarType = type
            user.save()
            message = "File Saved Successfully."
            redirect(action: 'show', params: [userId: userId])
        }
    }

我在保存>>>

之前尝试删除的服务操作
def String uploadFile( MultipartFile file, String name, String destinationDirectory ) {

    def serveletContext = ServletContextHolder.servletContext
    def storagePath = serveletContext.getRealPath( destinationDirectory )       
    def storagePathDirectory = new File("${storagePath}/${name}").delete()

    // 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
    }
}

我在控制器中的show方法>>>

def show = {
    Long uid = Long.parseLong(params.userId)
    def avatarUser = User.get(uid)
    String link = "user${avatarUser.id}.${avatarUser.avatarType}"
    [link:link]
}

我的观看页面>>>

    <g:if test="${link}">
         <img src="${resource(dir: 'assets/channelImage', file: "${link}")}" />
</g:if>

0 个答案:

没有答案