我想在我的webapplication中使用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 repository gridfs文件。
答案 0 :(得分:1)
这对我有用:
package ch.domain.vaadin;
import ch.domain.vaadin.mongo.MongoItem;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
/**
*
* @author eric
*/
class ImageUploader implements Receiver, SucceededListener {
private String filename;
private DB db;
private ByteArrayOutputStream fos;
private FieldGroup fieldGroup;
public void setFieldGroup(FieldGroup fieldGroup) {
this.fieldGroup = fieldGroup;
}
public ImageUploader(DB db)
{
this.db = db;
}
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
this.fos = new ByteArrayOutputStream();
this.filename = filename;
return this.fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(this.fos.toByteArray());
MongoItem parentId = (MongoItem) fieldGroup.getItemDataSource();
gfsFile.setMetaData(new BasicDBObject().append("parentId", parentId.getItemProperty("_id").getValue().toString()));
gfsFile.setFilename(this.filename);
gfsFile.save();
this.fos = null;
gfsFile = null;
// Show the uploaded file in the image viewer
// image.setVisible(true);
// image.setSource(new FileResource(file));
}
}