Java tutorial
/* Copyright 2006 - 2010 Under Dusken 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 no.dusken.common.view; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.view.AbstractView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.Map; public class FileView extends AbstractView { private final Logger log = LoggerFactory.getLogger(getClass()); protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response) throws IOException { // get the file from the map File file = (File) map.get("file"); // check if it exists if (file == null || !file.exists() || !file.canRead()) { log.warn("Error reading: {}", file); try { response.sendError(404); } catch (IOException e) { log.error("Could not write to response", e); } return; } // give some info in the response String mimeType; if (file.getName().contains(".image")) { mimeType = "image/jpeg"; } else { mimeType = getServletContext().getMimeType(file.getAbsolutePath()); } response.setContentType(mimeType); // files does not change so often, allow three days caching response.setHeader("Cache-Control", "public, max-age=2505600"); response.setContentLength((int) file.length()); // start writing to the response OutputStream outputStream = response.getOutputStream(); InputStream inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } }