file upload error

Hi
I am trying to upload file but getting the following error message:


java.lang.NullPointerException
    at com.company.demofileupload.gui.screens.Myfileupload.init(Myfileupload.java:31)
    at com.haulmont.cuba.gui.WindowManager.init(WindowManager.java:731)
    at com.haulmont.cuba.gui.WindowManager.initWrapperFrame(WindowManager.java:722)
    at com.haulmont.cuba.gui.WindowManager.createWindow(WindowManager.java:176)
    at com.haulmont.cuba.gui.WindowManager.openWindow(WindowManager.java:345)
    at com.haulmont.cuba.gui.config.MenuCommand.execute(MenuCommand.java:87)
    at com.haulmont.cuba.web.sys.MenuBuilder$1.menuSelected(MenuBuilder.java:153)
    at com.vaadin.ui.MenuBar.changeVariables(MenuBar.java:207)
    at com.vaadin.server.communication.ServerRpcHandler.changeVariables(ServerRpcHandler.java:508)
    at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:327)
    at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:202)
    at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:95)
    at com.haulmont.cuba.web.sys.CubaVaadinServletService$CubaUidlRequestHandler.lambda$synchronizedHandleRequest$67(CubaVaadinServletService.java:290)
    at com.haulmont.cuba.web.sys.CubaVaadinServletService$CubaUidlRequestHandler$$Lambda$11/103374517.call(Unknown Source)
    at com.haulmont.cuba.web.sys.CubaVaadinServletService.withUserSession(CubaVaadinServletService.java:171)
    at com.haulmont.cuba.web.sys.CubaVaadinServletService$CubaUidlRequestHandler.synchronizedHandleRequest(CubaVaadinServletService.java:290)
    at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
    at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1408)
    at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:356)
    at com.haulmont.cuba.web.sys.CubaApplicationServlet.serviceAppRequest(CubaApplicationServlet.java:226)
    at com.haulmont.cuba.web.sys.CubaApplicationServlet.service(CubaApplicationServlet.java:149)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.haulmont.cuba.web.sys.CubaHttpFilter.handleNotFiltered(CubaHttpFilter.java:100)
    at com.haulmont.cuba.web.sys.CubaHttpFilter.doFilter(CubaHttpFilter.java:87)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

I have created a screen file and copied the data from documentation to controller as follows:


/*
 * Copyright (c) 2016 demo-fileupload
 */
package com.company.demofileupload.gui.screens;

import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.FileStorageException;
import com.haulmont.cuba.gui.components.AbstractWindow;
import com.haulmont.cuba.gui.components.FileMultiUploadField;
import com.haulmont.cuba.gui.data.DataSupplier;
import com.haulmont.cuba.gui.upload.FileUploadingAPI;

import javax.inject.Inject;
import java.util.Map;
import java.util.UUID;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.haulmont.cuba.gui.components.AbstractLookup;
import com.haulmont.cuba.gui.components.AbstractFrame;

/**
 * @author Mortoza
 */
public class Myfileupload extends AbstractWindow {

    @Inject
    private FileMultiUploadField multiUploadField;
    @Inject
    private FileUploadingAPI fileUploadingAPI;
    @Inject
    private DataSupplier dataSupplier;

    @Override
    public void init(Map<String, Object> params) {
        multiUploadField.addQueueUploadCompleteListener(() -> {
            for (Map.Entry<UUID, String> entry : multiUploadField.getUploadsMap().entrySet()) {
                UUID fileId = entry.getKey();
                String fileName = entry.getValue();
                FileDescriptor fd = fileUploadingAPI.getFileDescriptor(fileId, fileName);
                // save file to FileStorage
                try {
                    fileUploadingAPI.putFileIntoStorage(fileId, fd);
                } catch (FileStorageException e) {
                    new RuntimeException("Error saving file to FileStorage", e);
                }
                // save file descriptor to database
                dataSupplier.commit(fd);
            }
            showNotification("Uploaded files: " + multiUploadField.getUploadsMap().values(), NotificationType.HUMANIZED);
            multiUploadField.clearUploads();
        });

        multiUploadField.addFileUploadErrorListener(event ->
                showNotification("File upload error", NotificationType.HUMANIZED));
    }

}

I just fixed the error and file is now uploaded. But i don’t see any file name that has been uploaded. How can I display the file name and an icon? Can I save it to database?

Here’s some code I use to upload a file and save it to storage:
uploadReferenceField.addFileUploadSucceedListener(event -> {
FileDescriptor fd = uploadReferenceField.getFileDescriptor();
try {
// save file to FileStorage
fileUploadingAPI.putFileIntoStorage(uploadReferenceField.getFileId(), fd);
} catch (FileStorageException e) {
throw new RuntimeException(“Error saving file to FileStorage”, e);
}
// save file descriptor to database and assign it to “content” property
getItem().setReferenceFileContents(dataManager.commit(fd));
txtReferenceFile.setValue(uploadReferenceField.getFileName());
showNotification("Uploaded file: " + uploadReferenceField.getFileName(), NotificationType.HUMANIZED);
});

Hi
Thanks. which event do you use to save it?

I used postInit().
so the method should be:
@Override
protected void postInit() {
super.postInit();
//insert the code above here.

}

Thanks . How do you specify the filed name of the entity where the file will be saved?

Not sure I understand, but once the files are uploaded, they are stored in the external storage. You can see them by going to Administration -> External Files.
Also, when you upload them, you should be getting a file descriptor. It is that file descriptor that you save to your entity if your entity expects a file descriptor. But you can always get the files from storage by doing something like this:
fileStorageService.loadFile(fileDescriptor);

Ok. Can you give a hints How can an entity be set to expect file descriptor?

very easy. When you create an entity, let’s say “MyFiles”.
MyFiles entity will have File1 and File2 attributes to store the files. You would need to set them as File Descriptor.
To do that, when you create File1 atrribute, choose the Attribute Type to be ASSOCIATION, type File Descriptor, Cardinality MANY-TO-ONE.

Hi
I have created the entity as indicated. But something is wrong in my code. I am getting the following error:

Errors in compiling:


:app-gui:compileJavaC:\inteaccweb\CubaProject\demo-fileupload\modules\gui\src\com\company\demofileupload\gui\employee\EmployeeEdit.java:46: error:  expected         uploadReferenceField.addFileUploadSucceedListener(event -> {                                                          ^ C:\inteaccweb\CubaProject\demo-fileupload\modules\gui\src\com\company\demofileupload\gui\employee\EmployeeEdit.java:46: error: not a statement         uploadReferenceField.addFileUploadSucceedListener(event -> {                                                           ^ C:\inteaccweb\CubaProject\demo-fileupload\modules\gui\src\com\company\demofileupload\gui\employee\EmployeeEdit.java:70: error: ';' expected         });          ^ 3 errors  FAILED 

Controller file contents:


/*
 * Copyright (c) 2016 demo-fileupload
 */
package com.company.demofileupload.gui.employee;

import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.core.global.FileStorageException;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.company.demofileupload.entity.Employee;
import com.haulmont.cuba.gui.components.FileUploadField;
import com.haulmont.cuba.gui.components.TextField;
import com.haulmont.cuba.gui.data.DataSupplier;
import com.haulmont.cuba.gui.upload.FileUploadingAPI;

import javax.inject.Inject;

/**
 * @author mortoza
 */
public class EmployeeEdit extends AbstractEditor<Employee> {


    @Override

    protected void postInit() {

        super.postInit();

        @Inject
        private FileUploadField uploadReferenceField;

        @Inject
        private FileUploadingAPI fileUploadingAPI;

        @Inject
        private TextField txtReferenceFile;

        @Inject
        private DataSupplier dataSupplier;

        @Inject
        private DataManager dataManager;

        @Override
        uploadReferenceField.addFileUploadSucceedListener(event -> {

            FileDescriptor fd = uploadReferenceField.getFileDescriptor();

            try {

// save file to FileStorage

                fileUploadingAPI.putFileIntoStorage(uploadReferenceField.getFileId(), fd);

            } catch (FileStorageException e) {

                throw new RuntimeException("Error saving file to FileStorage", e);

            }

// save file descriptor to database and assign it to "content" property

            getItem().setReferenceFileContents(dataManager.commit(fd));

            txtReferenceFile.setValue(uploadReferenceField.getFileName());

            showNotification("Uploaded file: " + uploadReferenceField.getFileName(), NotificationType.HUMANIZED);

        });


    }


}

entity file:


/*
 * Copyright (c) 2016 demo-fileupload
 */
package com.company.demofileupload.entity;

import javax.persistence.Entity;
import javax.persistence.Table;
import com.haulmont.cuba.core.entity.FileDescriptor;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.chile.core.annotations.NamePattern;

/**
 * @author mortoza
 */
@NamePattern("%s|emplName")
@Table(name = "DEMOFILEUPLOAD_EMPLOYEE")
@Entity(name = "demofileupload$Employee")
public class Employee extends StandardEntity {
    private static final long serialVersionUID = -3449993219836923329L;

    @Column(name = "EMPL_CODE", length = 10)
    protected String emplCode;

    @Column(name = "EMPL_NAME")
    protected String emplName;

    @Column(name = "DEPARTMENT", length = 100)
    protected String department;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PHOTOGRAPH_ID")
    protected FileDescriptor photograph;

    public void setEmplCode(String emplCode) {
        this.emplCode = emplCode;
    }

    public String getEmplCode() {
        return emplCode;
    }

    public void setEmplName(String emplName) {
        this.emplName = emplName;
    }

    public String getEmplName() {
        return emplName;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getDepartment() {
        return department;
    }

    public void setPhotograph(FileDescriptor photograph) {
        this.photograph = photograph;
    }

    public FileDescriptor getPhotograph() {
        return photograph;
    }


}

I have attached the project if you want to take a further look.

demo-fileupload.7z (112.7K)

Your code is wrong: Here’s my code:
@Inject
protected FileUploadField uploadReferenceField;

@Inject
protected FileUploadingAPI fileUploadingAPI;

@Inject
private FileStorageService fileStorageService;

@Inject
private DataManager dataManager;


@Override
protected void postInit() {
    super.postInit();

    uploadReferenceField.addFileUploadSucceedListener(event -> {
        FileDescriptor fd = uploadReferenceField.getFileDescriptor();
        try {
            // save file to FileStorage
            fileUploadingAPI.putFileIntoStorage(uploadReferenceField.getFileId(), fd);
        } catch (FileStorageException e) {
            throw new RuntimeException("Error saving file to FileStorage", e);
        }
        // save file descriptor to database and assign it to "content" property
        getItem().setReferenceFileContents(dataManager.commit(fd));
        txtReferenceFile.setValue(uploadReferenceField.getFileName());
        showNotification("Uploaded file: " + uploadReferenceField.getFileName(), NotificationType.HUMANIZED);
    });
}

Hi
Thanks. But I am getting the following erroes


   super.postInit(); 

The following lines are red, can not resolve…
getItem().setReferenceFileContents(dataManager.commit(fd));
txtReferenceFile.setValue(uploadReferenceField.getFileName()

error: can not resolve method super.postinit()

it should be super.postInit().

It’s an i uppercase.

Yes, I used the same postInit()
haven’t work.