10Download and Upload

One minute example: download

The following example shows how to expose the file to be downloaded to its client. Again, see how simple this code is:

@Resource
public class ProfileController {

    public File picture(Profile profile) {
        return new File("/path/to/the/picture." + profile.getId()+ ".jpg");
    }
}

Adding more info to download

If you want to add more information to download, you can return a FileDownload:

@Resource
public class ProfileController {

    public Download picture(Profile profile) {
        File file = new File("/path/to/the/picture." + profile.getId()+ ".jpg");
        String contentType = "image/jpg";
        String filename = profile.getName() + ".jpg";

        return new FileDownload(file, contentType, filename);
    }
}

You can also use the InputStreamDownload implementation to work with Streams or ByteArrayDownload to work with byte array (since 3.2-snapshot).

Upload

The upload component is optional. To enable this feature, you only need to add the commons-upload library in your classpath. Since VRaptor 3.2, if you're in a container that implements the JSR-315 (Servlet 3.0), you don't need commons-upload nor commons-io libraries because the servlet container already have this.

One minute example: upload

The first example is based on the multipart upload feature.

@Resource
public class ProfileController {

    private final ProfileDao dao;

    public ProfileController(ProfileDao dao) {
        this.dao = dao;
    }

    public void updatePicture(Profile profile, UploadedFile picture) {
        dao.update(picture.getFile(), profile);
        //The stream must be closed
        picture.getFile().close();
    }
}

More about Upload

UploadedFile returns the file content as a InputStream. If you want to save this file on disk in an easy way, you can use the commons-io IOUtils:

public void updatePicture(Profile profile, UploadedFile picture) {
    File pictureOnDisk = new File();
    IOUtils.copyLarge(picture.getFile(), new FileOutputStream(pictureOnDisk));
    dao.atribui(pictureOnDisk, profile);
}

Overriding upload settings

You can also change the default upload settings overriding the class MultipartConfig. In example below, the size limit of upload is changed.

@Component
@ApplicationScoped
public class CustomMultipartConfig extends DefaultMultipartConfig {

    public long getSizeLimit() {
        return 50 * 1024 * 1024; // 50MB
    }

}

Changes in form

You need to add the parameter enctype with multipart/form-data value. Without this attribute, the browser cannot upload files:

<form action="minha-action" method="post" enctype="multipart/form-data">

Validating upload

When the maximum size for uploaded file exceeds the configured value, VRaptor add a message on the Validator object.