如何从.gsp文件的形式上传照片,将其保存到某个文件夹并将其链接保存到数据库?

问题描述 投票:0回答:1

到目前为止,我已经尝试使用:在控制器上:

if(employeeInstance.save (flush:true)) {
    def profilePicture = request.getFile('profilePicture')
        if (!profilePicture.isEmpty()) {
            userInstance.avatar = fileUploadService.uploadFile(profilePicture, "${userInstance.id}.png", "profilePicture")
        }
    }

在这段代码中,我在request.getFile('profilePicture')时出错,因为我在请求时执行“ ctrl + space”时,我的IDE没有给getFile('')提供任何选项。 在.gsp文件中:

<form action="save">
    <input type='file' name='profilePicture'/>
    <input type='submit'/>
</form>

服务中:

import org.springframework.web.multipart.MultipartFile
import org.codehaus.groovy.grails.web.context.ServletContextHolder

class FileUploadService {
    boolean transactional = true

        def String uploadFile(MultipartFile file, String name, String destinationDirectory) {

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

            // Create storage path directory if it does not exist
            def storagePathDirectory = new File(storagePath)
            if (!storagePathDirectory.exists()) {
                print "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
            }
        }
}

所以我被困在这里任何帮助上传图像到某个驱动器,然后将该图像的链接保存在mysql数据库中?

grails file-upload gsp
1个回答
0
投票

首次使用g:uploadForm不能使用表格,或在表格中添加

`enctype='multipart/form-data'`

您可以找到的项目的基本目录

System.properties['base.dir']

希望它能对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.