3
我想在我的web應用中使用vaadin上傳組件,並直接上傳文件到mfs格式的mongo數據庫。Vaadin上傳組件 - 直接上傳到mongo倉庫
我目前的實現使用臨時存儲位置首先上傳文件,然後存儲在mongo中轉換爲gridfs。
這裏是我的上傳組件的代碼:我實現接收器接口方法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;
}
這裏是我的代碼在蒙戈庫
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。我認爲你可以做到這一點。 – sergiofbsilva