How to set the content type on the servlet

前端 未结 2 1397
离开以前
离开以前 2020-12-03 12:01

I am using a simple servlet which sends back document contents from the database as a byte array. I would like to set a content type so that it has an appropriate extension

2条回答
  •  时光取名叫无心
    2020-12-03 12:43

    What should I set as the content type so that it retains the file extension?

    Use ServletContext#getMimeType() to get the mime type based on the file name.

    String mimeType = getServletContext().getMimeType(filename);
    

    The servletcontainer usually already provides a default mime type mapping in its own web.xml. If you want to overridde or add some other, then put it as new mime mappings in webapp's web.xml. E.g.

    
        docx
        application/vnd.openxmlformats-officedocument.wordprocessingml.document
    
    
        xlsx
        application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    
    

    Finally set it as the Content-Type response header:

    response.setContentType(mimeType);
    

    The file gets downloaded with a name of "doc", how do I set the filename on the servlet for the data being downloaded.

    Add it to the servlet URL because some browsers like MSIE ignores the filename attribute of the content disposition.

    download filename.ext
    

    If the servlet is mapped on an URL pattern of /download/*, then you can obtain it as follows

    String filename = request.getPathInfo().substring(1);
    

    Finally set it in the Content-Disposition header as well to make normal browsers happy:

    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    

    If you don't store filenames in DB but rather IDs or something, then use it as filename instead.

    download ${file.id}.${file.ext}
    

    And then in the servlet

    String filename = request.getPathInfo().substring(1);
    String id = filename.split("\\.")[0];
    // Obtain from DB based on id.
    

提交回复
热议问题