将 CommonsMultipartFile 保存到数据库
我正在尝试使用 JPA 将上传的文件保存到数据库。最“自然”的方法(对我来说)是将域对象定义为:
@Entity
class UploadFile {
...
public CommonsMultipartFile getFileData()
{
return fileData;
}
}
但这不起作用,因为没有这样的数据库映射类型。在网上搜索,我发现人们似乎采用了两种方法之一:
- 将字段定义为
java.sql.blob;
- 将字段定义为
byte[]
在 < code>@Controller 类,传入的 HttpServletRequest
被强制转换为 MultipartHttpServletRequest
,以便访问 MultipartFile
并将其转换回 代码>字节[]流。
然而,使用这个方案,我得到了让我困惑的“随机”结果:时不时地,我遇到“bean属性不可读”错误,byte[]字段上的getter方法的返回类型可能不匹配。我仔细检查了 Bean 的定义,没有发现任何错误。
我想我的问题有两个:(1)知道为什么在这种情况下会发生这个错误吗? (2)更重要的是,处理这样上传的文件的“推荐”方式是什么?
谢谢
奥利弗
I am trying to persist a uploaded file to database using JPA. The most "natural" way (to me) is to define domain object as:
@Entity
class UploadFile {
...
public CommonsMultipartFile getFileData()
{
return fileData;
}
}
But this won't work since there is not such a database mapping type. Searching online, I found that people seems to adapt one of the two methods:
- Define the field as
java.sql.blob;
- Define the field as
byte[]
In the @Controller
class, the incoming HttpServletRequest
gets cast to MultipartHttpServletRequest
in order to access the MultipartFile
and convert it back to byte[]
stream.
However, with this scheme, I have "random" results which puzzles me: from time to time, I ran into "bean property not readable" error, possible mismatch of return type of getter method on the byte[] field. I double and triple checked my Bean definition, and couldn't find anything wrong.
I guess my questions are two folds: (1) Any idea why this error can happen in this context? (2) more importantly, what are the "recommended" way of handling uploaded file like this?
thanks
Oliver
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是正确的,
java.sql.blob
或byte[]
是将上传文件存储在数据库中的最合适方法。您不应将
MultipartFile
或CommonsMultipartFile
存储在数据库中,因为它们是临时对象。请注意MultipartFile
javadoc 中的这一点:我不太明白您对 HttpServletRequest 所做的事情,但这听起来不是处理上传的最简单方法。处理上传的最简单方法是使
MultipartFile
成为控制器方法上的参数(我认为,如果您使用的是 Spring 3.0 或更高版本):这应该可靠地工作,因为您已经提取了在请求完成之前,也就是在删除用于处理上传的任何临时文件之前,将字节写入您的
byte[]
数组中。You are correct that either a
java.sql.blob
or abyte[]
would be the most appropriate way to store an uploaded file in a database.You should not store a
MultipartFile
or aCommonsMultipartFile
in a database because these are intended to be temporary objects. Note this from theMultipartFile
javadoc:I don't quite follow what you're doing with your
HttpServletRequest
but it doesn't sound like the easiest way to handle the upload. The easiest way to handle an upload is to make theMultipartFile
a parameter on your controller method (if you're using Spring 3.0 or later, I think):This should work reliably because you've extracted the bytes into your
byte[]
array before the request has finished — and thus before the any temporary files used to handle the upload have been deleted.