我需要将图像保存到应用程序中的文件夹中。到目前为止,我已经学会了将图像保存到数据库中,但是我需要将其保存到文件夹中。我怎样才能做到这一点?谁能帮我这个忙吗?这是我下面的代码,保存到数据库中>>>
def upload={
def user = User.findById(1)
CommonsMultipartFile file = params.list("photo")?.getAt(0)
user.avatar = file?.bytes
user.save()
}
最佳答案
在下面查找逐步实现的方法,我添加了一个带有uploadForm的GSP页面(默认情况下将进行多部分表单提交),然后是一个 Controller 函数来处理文件保存请求,以及一种将文件保存到指定目录中的服务方法:
步骤1:建立文件上载表格:
<g:uploadForm name="picUploadForm" class="well form-horizontal" controller="<your-controller-name>" action="savePicture">
Select Picture: <input type="file" name="productPic"/>
<button type="submit" class="btn btn-success"><g:message code="shopItem.btn.saveProductImage" default="Save Image" /></button>
</g:uploadForm>
步骤2:然后在 Controller 的savePicture Action 中:
String baseImageName = java.util.UUID.randomUUID().toString();
// Saving image in a folder assets/channelImage/, in the web-app, with the name: baseImageName
def downloadedFile = request.getFile( "product.baseImage" )
String fileUploaded = fileUploadService.uploadFile( downloadedFile, "${baseImageName}.jpg", "assets/channelImage/" )
if( fileUploaded ){
// DO further actions, for example make a db entry for the file name
}
步骤3:并在文件上传器服务中(在这种情况下,用户定义的服务名为FileUploadService):
def String uploadFile( MultipartFile file, String name, String destinationDirectory ) {
def serveletContext = ServletContextHolder.servletContext
def storagePath = serveletContext.getRealPath( destinationDirectory )
def storagePathDirectory = new File( storagePath )
if( !storagePathDirectory.exists() ){
println("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
}
}
关于image - 在grails中将图像保存到Web应用程序下的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17829413/