我有一个模型实体Image
实体的字段类型为:Blob
要执行文件上传,请使用Apache Commons FileUpload Library
要获取我的文件,我使用以下代码:
Image image = new Image();
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(req);
while(itr.hasNext()){
FileItemStream item = itr.next();
if(!item.isFormField())
{
image.setImageType(item.getContentType());
InputStream stream = item.openStream();
image.setImageData(???); //How to Set Blob Data from Input Stream
}
}
} catch (FileUploadException e) {
resp.sendError(500);
}
感谢。
答案 0 :(得分:0)
使用Apache Commons FileUpload附带的Streams.copy(input, output, doClose)
实用程序方法将InputStream
复制到字节数组中并从中创建Blob
:
InputStream stream = ...
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Streams.copy(stream, bytes, true /* close stream after copy */);
Blob blob = new Blob(bytes.toByteArray());
image.setImageData(blob);