在下面找到逐步实现,我添加了一个带有uploadForm的GSP页面(默认情况下它将具有多部分表单提交),然后是一个处理文件保存请求的控制器函数,以及一个将文件保存在指定目录中的服务方法:
Step1:创建文件上传表单:
<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>
Step2:然后在控制器的 savePicture 操作中:
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
}
Step3:在文件上传服务中(在这种情况下,用户定义的服务名称为 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
}
}