org.freeeed.ep.web.controller.FileDownloadController.java Source code

Java tutorial

Introduction

Here is the source code for org.freeeed.ep.web.controller.FileDownloadController.java

Source

/*
 *
 * Copyright SHMsoft, Inc. 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package org.freeeed.ep.web.controller;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.ServletOutputStream;

import org.apache.log4j.Logger;
import org.freeeed.ep.web.BaseController;
import org.freeeed.ep.web.WebConstants;
import org.springframework.web.servlet.ModelAndView;

public class FileDownloadController extends BaseController {
    private static final Logger log = Logger.getLogger(FileDownloadController.class);

    private String workDir;

    @Override
    public ModelAndView execute() {
        String result = (String) valueStack.get("file");
        String resultFile = workDir + File.separator + result;

        File toDownload = new File(resultFile);

        try {
            int length = 0;
            ServletOutputStream outStream = response.getOutputStream();
            String mimetype = "application/octet-stream";

            response.setContentType(mimetype);
            response.setContentLength((int) toDownload.length());
            String fileName = toDownload.getName();

            // sets HTTP header
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            byte[] byteBuffer = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(toDownload));

            // reads the file's bytes and writes them to the response stream
            while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
                outStream.write(byteBuffer, 0, length);
            }

            in.close();
            outStream.close();
        } catch (Exception e) {
            log.error("Problem sending cotent", e);
            valueStack.put("error", true);
        }

        return new ModelAndView(WebConstants.DOWNLOAD_RESULT);
    }

    public void setWorkDir(String workDir) {
        this.workDir = workDir;
    }
}