javaliteactiveweb

Any example of uploading files using activeweb?


I try to upload some csv files to server side and process them and save to database, any example about uploading file in activeweb?


Solution

  • The Kitchensink example has an upload demo: https://github.com/javalite/kitchensink.

    Here is the sample of code that can process multipart POST request:

    public class UploadController extends AppController {
    
        public void index() {}
    
        @POST
        public void save() throws IOException {
            List<FormItem> items = multipartFormItems();
            List<String> messages = new ArrayList<String>();
    
            for (FormItem item : items) {
                if(item.isFile()){
                    messages.add("Found file: " + item.getFileName() + " with size: " + Util.read(item.getInputStream()).length());
                }else{
                    messages.add("Found field: " + item.getFieldName() + " with value: " + item.getStreamAsString());
                }
            }
            flash("messages", messages);
            redirect(UploadController.class);
        }
    }
    

    On the Freemarker side:

    <@form controller="upload" action="save" method="post" enctype="multipart/form-data">
        Select a file to upload:<input type="file" name="file">
    
    <input name="book" value="The Great Gatsby" type="text">
        <button>Upload File</button>
    </@>
    

    I hope this code is easy to follow.