Java Code Examples for javax.servlet.ServletContext#getMimeType()

The following examples show how to use javax.servlet.ServletContext#getMimeType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResponseUtils.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Prepares download of a file. The content type will be detected automatically by the file name.
 *
 * @param filename Virtual file name. Any path infos will be truncated.
 * @param response
 * @param ctx der Servletcontext
 * @param attach Download as Attachment
 */
public static void prepareDownload(String filename, HttpServletResponse response, ServletContext ctx, boolean attach)
{
  String mimeType = null;
  try {
    mimeType = ctx.getMimeType(filename);
  } catch (Exception ex) {
    log.info("Exception while getting mime-type (using application/binary): " + ex);
  }
  if (mimeType == null) {
    response.setContentType("application/binary");
  } else {
    response.setContentType(mimeType);
  }
  log.debug("Using content-type " + mimeType);
  final String filenameWithoutPath = FilenameUtils.getName(filename);
  if (attach == true) {
    response.setHeader("Content-disposition", "attachment; filename=\"" + filenameWithoutPath + "\"");
  } else {
    response.setHeader("Content-disposition", "inline; filename=\"" + filenameWithoutPath + "\"");
  }
}
 
Example 2
Source File: JnlpResource.java    From webstart with MIT License 6 votes vote down vote up
private String getMimeType( ServletContext context, String path )
{
    String mimeType = context.getMimeType( path );
    if ( mimeType != null )
    {
        return mimeType;
    }
    if ( path.endsWith( _jnlpExtension ) )
    {
        return JNLP_MIME_TYPE;
    }
    if ( path.endsWith( _jarExtension ) )
    {
        return JAR_MIME_TYPE;
    }
    return "application/unknown";
}
 
Example 3
Source File: DownloadServlet(简单的文件下载).java    From java_study with Apache License 2.0 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 1.获取请求参数,文件名称
    String filename = request.getParameter("filename");
    // 2.使用字节输入流加载文件进内存
    // 2.1找到文件服务器路径
    ServletContext servletContext = this.getServletContext();
    String realPath = servletContext.getRealPath("/img/" + filename);
    // 2.2用字节流关联
    FileInputStream fis = new FileInputStream(realPath);
    // 3.设置response的响应头
    // 3.1设置响应头类型:content-type
    String mimeType = servletContext.getMimeType(filename); //获取文件的mime类型
    response.setHeader("content-type", mimeType);
    // 3.2设置响应头打开方式:content-disposition
    // 解决中文文件名问题
    // 1.获取user-agent请求头、
    String agent = request.getHeader("user-agent");
    // 2.使用工具类方法编码文件名即可
    filename = DownLoadUtils.getFileName(agent, filename);
    response.setHeader("content-disposition","attachment;filename="+filename);
    //4.将输入流的数据写出到输出流中
    ServletOutputStream sos = response.getOutputStream();
    byte[] buff = new byte[1024 * 8];
    int len = 0;
    while((len = fis.read(buff)) != -1){
        sos.write(buff, 0, len);
    }
    fis.close();
}
 
Example 4
Source File: StorageHandler.java    From wings with Apache License 2.0 5 votes vote down vote up
public static Response streamFile(String location, ServletContext context) {
   final File f = new File(location);
   if(!f.exists())
     return Response.status(Status.NOT_FOUND).build();
   if(!f.canRead()) 
     return Response.status(Status.FORBIDDEN).build();
   
   StreamingOutput stream = new StreamingOutput() {
     @Override
     public void write(OutputStream os) throws IOException {
       try {
         if(f.isDirectory())
           StorageHandler.streamDirectory(f, os);
         else
           StorageHandler.streamFile(f, os);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   };
   
   String filename = f.getName();
   String mime = context.getMimeType(f.getAbsolutePath());
   if(f.isDirectory()) {
     filename += ".zip";
     mime = "application/zip";
   }
   
   return Response.ok(stream, mime)
       .header("content-disposition", "attachment; filename = "+ filename)
       .build();
}
 
Example 5
Source File: StyleSheetFileServlet.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws IOException
 */
protected void processRequest( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
    AdminUser user = AdminUserService.getAdminUser( request );

    // FIXME : use a jsp instead of a servlet to control the right in a standard way
    if ( ( user != null ) && ( user.checkRight( StyleSheetJspBean.RIGHT_MANAGE_STYLESHEET ) ) )
    {
        String strStyleSheetId = request.getParameter( Parameters.STYLESHEET_ID );

        if ( strStyleSheetId != null )
        {
            int nStyleSheetId = Integer.parseInt( strStyleSheetId );

            StyleSheet stylesheet = StyleSheetHome.findByPrimaryKey( nStyleSheetId );

            ServletContext context = getServletConfig( ).getServletContext( );
            String strMimetype = context.getMimeType( stylesheet.getFile( ) );
            response.setContentType( ( strMimetype != null ) ? strMimetype : "application/octet-stream" );
            response.setHeader( "Content-Disposition", "attachement; filename=\"" + stylesheet.getFile( ) + "\"" );

            OutputStream out = response.getOutputStream( );
            out.write( stylesheet.getSource( ) );
            out.flush( );
            out.close( );
        }
    }
}
 
Example 6
Source File: RequestDispatcherImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void serviceSSIResource(final String uri,
                                final HttpServletResponse response,
                                final ServletConfig config,
                                final boolean useGzip)
    throws IOException
{
  final String target = HttpUtil.makeTarget(uri, servletPath);
  final ServletContext context = config.getServletContext();

  final String contentType = context.getMimeType(target);
  if (contentType != null) {
    response.setContentType(contentType);
  }

  ServletOutputStream os = response.getOutputStream();
  if (useGzip) {
    os = new GZIPServletOutputStreamImpl(os);
    response.addHeader(HeaderBase.CONTENT_ENCODING, "gzip");
  }
  try {
    parseHtml(target, context, os, new Stack<String>());
  } catch (final IOException ioe) {
    throw ioe;
  } catch (final Exception e) {
    os.print("<b><font color=\"red\">SSI Error: " + e + "</font></b>");
  }
  // An explicit flush is needed here, since flushing the
  // underlying servlet output stream will not finish the gzip
  // process! Note flush() should only be called once on a
  // GZIPServletOutputStreamImpl.
  os.flush();
}
 
Example 7
Source File: SSIServlet.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Process our request and locate right SSI command.
 * 
 * @param req
 *            a value of type 'HttpServletRequest'
 * @param res
 *            a value of type 'HttpServletResponse'
 */
protected void requestHandler(HttpServletRequest req,
        HttpServletResponse res) throws IOException {
    ServletContext servletContext = getServletContext();
    String path = SSIServletRequestUtil.getRelativePath(req);
    if (debug > 0)
        log("SSIServlet.requestHandler()\n" + "Serving "
                + (buffered?"buffered ":"unbuffered ") + "resource '"
                + path + "'");
    // Exclude any resource in the /WEB-INF and /META-INF subdirectories
    // (the "toUpperCase()" avoids problems on Windows systems)
    if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF")
            || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        log("Can't serve file: " + path);
        return;
    }
    URL resource = servletContext.getResource(path);
    if (resource == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        log("Can't find file: " + path);
        return;
    }
    String resourceMimeType = servletContext.getMimeType(path);
    if (resourceMimeType == null) {
        resourceMimeType = "text/html";
    }
    res.setContentType(resourceMimeType + ";charset=" + outputEncoding);
    if (expires != null) {
        res.setDateHeader("Expires", (new java.util.Date()).getTime()
                + expires.longValue() * 1000);
    }
    req.setAttribute(Globals.SSI_FLAG_ATTR, "true");
    processSSI(req, res, resource);
}
 
Example 8
Source File: UploadDownloadFileServlet.java    From journaldev with MIT License 5 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String fileName = request.getParameter("fileName");
	if(fileName == null || fileName.equals("")){
		throw new ServletException("File Name can't be null or empty");
	}
	File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
	if(!file.exists()){
		throw new ServletException("File doesn't exists on server.");
	}
	System.out.println("File location on server::"+file.getAbsolutePath());
	ServletContext ctx = getServletContext();
	InputStream fis = new FileInputStream(file);
	String mimeType = ctx.getMimeType(file.getAbsolutePath());
	response.setContentType(mimeType != null? mimeType:"application/octet-stream");
	response.setContentLength((int) file.length());
	response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
	
	ServletOutputStream os       = response.getOutputStream();
	byte[] bufferData = new byte[1024];
	int read=0;
	while((read = fis.read(bufferData))!= -1){
		os.write(bufferData, 0, read);
	}
	os.flush();
	os.close();
	fis.close();
	System.out.println("File downloaded at client successfully");
}
 
Example 9
Source File: MediaTypeUtil.java    From fake-smtp-server with Apache License 2.0 5 votes vote down vote up
public MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) {
    var mineType = servletContext.getMimeType(fileName);
    try {
        return MediaType.parseMediaType(mineType);
    } catch (Exception e) {
        return MediaType.APPLICATION_OCTET_STREAM;
    }
}
 
Example 10
Source File: MediaTypeUtils.java    From nbp with Apache License 2.0 5 votes vote down vote up
public static MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) {
    // application/pdf
    // application/xml
    // image/gif, ...
    String mineType = servletContext.getMimeType(fileName);
    try {
        MediaType mediaType = MediaType.parseMediaType(mineType);
        return mediaType;
    } catch (Exception e) {
        return MediaType.APPLICATION_OCTET_STREAM;
    }
}
 
Example 11
Source File: SSIServlet.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Process our request and locate right SSI command.
 * 
 * @param req
 *            a value of type 'HttpServletRequest'
 * @param res
 *            a value of type 'HttpServletResponse'
 */
protected void requestHandler(HttpServletRequest req,
        HttpServletResponse res) throws IOException {
    ServletContext servletContext = getServletContext();
    String path = SSIServletRequestUtil.getRelativePath(req);
    if (debug > 0)
        log("SSIServlet.requestHandler()\n" + "Serving "
                + (buffered?"buffered ":"unbuffered ") + "resource '"
                + path + "'");
    // Exclude any resource in the /WEB-INF and /META-INF subdirectories
    // (the "toUpperCase()" avoids problems on Windows systems)
    if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF")
            || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        log("Can't serve file: " + path);
        return;
    }
    URL resource = servletContext.getResource(path);
    if (resource == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        log("Can't find file: " + path);
        return;
    }
    String resourceMimeType = servletContext.getMimeType(path);
    if (resourceMimeType == null) {
        resourceMimeType = "text/html";
    }
    res.setContentType(resourceMimeType + ";charset=" + outputEncoding);
    if (expires != null) {
        res.setDateHeader("Expires", (new java.util.Date()).getTime()
                + expires.longValue() * 1000);
    }
    req.setAttribute(Globals.SSI_FLAG_ATTR, "true");
    processSSI(req, res, resource);
}
 
Example 12
Source File: SysMenuController.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/media/", method=RequestMethod.GET)
	public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) {

		// Get your file stream from wherever.
		String fullPath = "E:/" + id +".rmvb";

		ServletContext context = request.getServletContext();

		// get MIME type of the file
		String mimeType = context.getMimeType(fullPath);
		if (mimeType == null) {
			// set to binary type if MIME mapping not found
			mimeType = "application/octet-stream";
			System.out.println("context getMimeType is null");
		}
		System.out.println("MIME type: " + mimeType);

		// set content attributes for the response
		response.setContentType(mimeType);
//		response.setContentLength((int) downloadFile.length());

		// set headers for the response
		String headerKey = "Content-Disposition";
		String headerValue = String.format("attachment; filename=\"%s\"",
				"test");
		response.setHeader(headerKey, headerValue);
		// Copy the stream to the response's output stream.
		try {
			InputStream myStream = new FileInputStream(fullPath);
			IOUtils.copy(myStream, response.getOutputStream());
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
Example 13
Source File: SSIServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Process our request and locate right SSI command.
 *
 * @param req
 *            a value of type 'HttpServletRequest'
 * @param res
 *            a value of type 'HttpServletResponse'
 * @throws IOException an IO error occurred
 */
protected void requestHandler(HttpServletRequest req,
        HttpServletResponse res) throws IOException {
    ServletContext servletContext = getServletContext();
    String path = SSIServletRequestUtil.getRelativePath(req);
    if (debug > 0)
        log("SSIServlet.requestHandler()\n" + "Serving "
                + (buffered?"buffered ":"unbuffered ") + "resource '"
                + path + "'");
    // Exclude any resource in the /WEB-INF and /META-INF subdirectories
    // (the "toUpperCase()" avoids problems on Windows systems)
    if (path == null || path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF")
            || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        log("Can't serve file: " + path);
        return;
    }
    URL resource = servletContext.getResource(path);
    if (resource == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        log("Can't find file: " + path);
        return;
    }
    String resourceMimeType = servletContext.getMimeType(path);
    if (resourceMimeType == null) {
        resourceMimeType = "text/html";
    }
    res.setContentType(resourceMimeType + ";charset=" + outputEncoding);
    if (expires != null) {
        res.setDateHeader("Expires", (new java.util.Date()).getTime()
                + expires.longValue() * 1000);
    }
    processSSI(req, res, resource);
}
 
Example 14
Source File: RequestDispatcherImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void serviceGet(Request request,
                        Response response,
                        ServletConfig config)
    throws IOException
{
  // Activator.log.info("serviceGet()");
  String uri =
    (String) request.getAttribute("javax.servlet.include.request_uri");
  if (uri == null) {
    uri = request.getRequestURI();
  }

  final boolean useGzip = HttpUtil.useGZIPEncoding(request);

  if (uri.endsWith(".shtml")) {
    serviceSSIResource(uri, response, config, useGzip);
  } else {


    final String target = HttpUtil.makeTarget(uri, servletPath);
    final ServletContext context = config.getServletContext();
    // final URL url = context.getResource(target);
    final URLConnection resource = resourceURL.openConnection();

    // HACK CSM
    final long date = getLastModified(resource);
    if (date > -1) {
      try {
        final long if_modified = request.getDateHeader("If-Modified-Since");
        if (if_modified > 0 && date / 1000 <= if_modified / 1000) {
          response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
          return;
        }
      } catch (final IllegalArgumentException iae) {
        // An 'If-Modified-Since' header is present but the value
        // can not be parsed; ignore it.
        final LogRef log = Activator.log;
        if (null != log && log.doDebug()) {
          log.debug("Ignoring broken 'If-Modified-Since' header: "
                        + iae.getMessage(), iae);
        }
      }
      response.setDateHeader("Last-Modified", date);
    }
    // END HACK CSM
    
    String contentType = context.getMimeType(target);
    
    if (contentType == null) {
      contentType = resource.getContentType();
    }
    
    if (contentType != null) {
      final String encoding = resource.getContentEncoding();
      if (encoding != null) {
        contentType += "; charset=" + encoding;
      }
      response.setContentType(contentType);
    }

    final InputStream is = resource.getInputStream();
    response.copy(is);
    is.close();
  }
}
 
Example 15
Source File: HttpServer.java    From hbase with Apache License 2.0 4 votes vote down vote up
/**
 * Infer the mime type for the response based on the extension of the request
 * URI. Returns null if unknown.
 */
private String inferMimeType(ServletRequest request) {
  String path = ((HttpServletRequest)request).getRequestURI();
  ServletContext context = config.getServletContext();
  return context.getMimeType(path);
}
 
Example 16
Source File: WebApplicationResource.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up
/**
 * Derives a mimetype from the filename within the given path using the
 * given ServletContext, if possible.
 *
 * @param context
 *     The ServletContext to use to derive the mimetype.
 *
 * @param path
 *     The path to derive the mimetype from.
 *
 * @return
 *     An appropriate mimetype based on the name of the file in the path,
 *     or "application/octet-stream" if no mimetype could be determined.
 */
private static String getMimeType(ServletContext context, String path) {

    // If mimetype is known, use defined mimetype
    String mimetype = context.getMimeType(path);
    if (mimetype != null)
        return mimetype;

    // Otherwise, default to application/octet-stream
    return "application/octet-stream";

}
 
Example 17
Source File: WebApplicationResource.java    From guacamole-client with Apache License 2.0 3 votes vote down vote up
/**
 * Derives a mimetype from the filename within the given path using the
 * given ServletContext, if possible.
 *
 * @param context
 *     The ServletContext to use to derive the mimetype.
 *
 * @param path
 *     The path to derive the mimetype from.
 *
 * @return
 *     An appropriate mimetype based on the name of the file in the path,
 *     or "application/octet-stream" if no mimetype could be determined.
 */
private static String getMimeType(ServletContext context, String path) {

    // If mimetype is known, use defined mimetype
    String mimetype = context.getMimeType(path);
    if (mimetype != null)
        return mimetype;

    // Otherwise, default to application/octet-stream
    return "application/octet-stream";

}