Компонент Vaadin Upload - прямая загрузка в репозиторий mongo

Я хочу использовать компонент загрузки vaadin в своем веб-приложении и напрямую загружать файлы в mongo db в формате gridfs.

Моя текущая реализация использует временное хранилище, чтобы сначала загрузить файл, а затем сохранить в монго, конвертируя в 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);
            }
        }
    }

Есть ли способ отказаться от использования временного хранилища и установить выходной поток компонента загрузки в файл gridfs репозитория mongo.


person Isuru    schedule 06.06.2012    source источник
comment
Почему вы не можете использовать код в saveBuildFile и сделать это в методе receiveUpload? ReceiveUpload просто должен вернуть OutputStream для файла, в который он будет записываться. Я думаю, у вас получится это сделать.   -  person sergiofbsilva    schedule 08.06.2012


Ответы (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));
    }
}
person ericg    schedule 07.12.2014