【发布时间】:2012-06-10 06:28:53
【问题描述】:
我想在我的 web 应用程序中使用 vaadin 上传组件,并以 gridfs 格式直接将文件上传到 mongo db。
我当前的实现使用临时存储位置首先上传文件,然后存储在 mongo 中转换为 gridfs。
这是我的上传组件代码:我已经实现了Receiver接口方法recieveUpload
private File file;
private String tempFilePath;
public class HandleUploadImpl extends CustomComponent
implements Upload.SucceededListener,
Upload.FailedListener,
Upload.ProgressListener,
Upload.Receiver { ........
public OutputStream receiveUpload(String filename, String MIMEType) {
logger.debug("File information {} {}", filename, MIMEType);
this.filename = filename;
FileOutputStream fos;
file = new File(tempFilePath + filename);
try {
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
logger.error("Error occurred while opening the file {}", e);
return null;
}
return fos;
}
这是我要存储在 mongo 存储库中的代码
private void saveBuildFile(Map<String, Object> buildFileInfo, String key) {
if (buildFileInfo.containsKey(key)) {
GridFS gridFS = new GridFS(mongoTemplate.getDb(), COLLECTION_NAME);
File file = (File) buildFileInfo.get(key);
buildFileInfo.remove(key);
try {
GridFSInputFile savedFile = gridFS.createFile(file);
savedFile.put(idK, buildFileInfo.get(key + "-id"));
savedFile.save();
} catch (Exception e) {
logger.error("Something went wrong when saving the file in the db {}", e);
}
}
}
有没有办法可以省略临时存储的使用,将上传组件的输出流设置为mongo存储库gridfs文件。
【问题讨论】:
-
为什么不能使用 saveBuildFile 中的代码并在 receiveUpload 方法中执行? receiveUpload 只需要在它将写入的文件上返回一个 OutputStream。我认为你可以做到。
标签: java mongodb upload vaadin gridfs