我需要将图像保存到我的应用程序的文件夹中。到目前为止,我已经学会了将图像保存到数据库中,但我需要将其保存到文件夹中。我怎样才能做到这一点?有人可以帮我吗?这是我下面保存到数据库中的代码>>>
def upload={
def user = User.findById(1)
CommonsMultipartFile file = params.list("photo")?.getAt(0)
user.avatar = file?.bytes
user.save()
}
我需要将图像保存到我的应用程序的文件夹中。到目前为止,我已经学会了将图像保存到数据库中,但我需要将其保存到文件夹中。我怎样才能做到这一点?有人可以帮我吗?这是我下面保存到数据库中的代码>>>
def upload={
def user = User.findById(1)
CommonsMultipartFile file = params.list("photo")?.getAt(0)
user.avatar = file?.bytes
user.save()
}
在下面找到逐步实现,我添加了一个带有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
}
}
您只需将 MutipartFile 复制到 web-app 文件夹中。这是如何:
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("myfile");
String fileName = System.currentTimeMillis() + f.name
String destinationFileName = configService.getAbsoluteDocumentsPath() + fileName // We will put it on web-app/documents/xxxxx
f.renameTo(new File(destinationFileName))
//Save filename to database in
user.avatar = fileName
user.save()
在 configService 我有那个(用于计算路径)
class ConfigService {
def grailsApplication
/**
* @return absolute path of documents
*/
def getAbsoluteDocumentsPath(){
def asolutePath = grailsApplication.mainContext.servletContext.getRealPath('documents')
return asolutePath.endsWith("/") ? asolutePath : asolutePath + "/"
}
}
编辑 以确保您的请求是 MutipartHttServletRequest 的实例添加以下测试
if(request instanceof MultipartHttpServletRequest) {
//Do stuff here
}
不要忘记检查您放置文件输入的表单的编码。
我很容易解决这个问题,如下所示。您将必须导入以下内容:
导入 org.apache.commons.io.FileUtils
导入 org.springframework.web.multipart.commons.CommonsMultipartFile
导入 org.springframework.web.multipart.*
祝需要这个的人好运>>>
def saveImageToFolder = {
String message = ""
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("userPhoto")
if(!f.empty) {
def usr = User.findByUsername(1)
if(!usr){
User user = new User()
user.username = params.username
user.avatarType = f.getContentType()
if(user.save()){
def userId = user.id
String username = user.username
String fileName = username + "." + f.getContentType().substring(6) // here my file type is image/jpeg
byte[] userImage = f.getBytes()
FileUtils.writeByteArrayToFile(new File( grailsApplication.config.images.location.toString() + File.separatorChar + fileName ), userImage )
message = "User Created Successfully."
}else{
message = "Can not Create User !!!"
}
}else{
message = "Username already exists. Please try another one !!!"
}
}
else {
message = 'file cannot be empty'
}
render(view: 'addUser', model:[message: message])
}
并在你的配置文件中粘贴这个>>>
images.location = "web-app/images/userImages/" // after web-app/folder name/folder name and go on if you want to add other folder