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

我在控制器中的显示方法 >>>

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>
4

0 回答 0