【发布时间】: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