0

I have .pdf,.jpg,.docx files and I want to open them when button clicked. Is there any method to set multiple content types in servlet. My servlet codes like this.

String Docpath=request.getParameter("document");
String docname=request.getParameter("docName");

response.setContentType("application/pdf");
response.setHeader("Content-Disposition","inline;filename="+docname);

BufferedInputStream bis=null;
BufferedOutputStream bos=null;

try{
    ServletOutputStream outs=response.getOutputStream();
    File file=new File("T:\\Temp\\"+docname);
    File original=new File(Docpath);
    File destination=new File("T:\\Temp\\");
    FileUtils.copyFileToDirectory(original,destination);
    InputStream input=new FileInputStream(file);
    bis=new BufferedInputStream(input);
    bos=new BufferedOutputStream(outs);
    byte[]buf=new byte[2048];

    int bytesRead;
    while((bytesRead=bis.read(buf))>0) {
        bos.write(buf,0,bytesRead);
    }
} catch(IOException e) {
    e.printStackTrace();
} finally {
    bis.close();
    bos.close();
}

There is the working codes

File file=new File("T:\\Temp\\"+docname);
Path filePath=Paths.get("T:\\Temp\\"+docname);
response.setContentType(Files.probeContentType(filePath));

1 Answers1

2

You can not set multiple content types. What you need to do is to determine the content type of the file you load from disk:

File file=new File("T:\\Temp\\"+docname);

After you find out what the content type is you set it:

response.setContentType(contentTypeOfTheFileIJustLoaded);

There are a few options how you can find out the content type of a file. Have a look at the following Stackoverflow question:

Getting A File's Mime Type In Java

Jens
  • 20,533
  • 11
  • 60
  • 86