【问题标题】:How to upload a photo from form of .gsp file save it to some folder and save its link to database?如何从 .gsp 文件形式上传照片将其保存到某个文件夹并将其链接保存到数据库?
【发布时间】:2015-02-02 17:33:34
【问题描述】:

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

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】:

    对于第一次使用 g:uploadForm 不是表格,或者在表格中添加

    `enctype='multipart/form-data'`
    

    你可以通过

    找到的项目基础目录
    System.properties['base.dir']
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 2012-11-17
      相关资源
      最近更新 更多