在java servlet中设置多个内容类型
我有.pdf、.jpg、.docx文件,我想在单击按钮时打开它们。是否有任何方法可以在servlet中设置多个内容类型。我的servlet代码如下在java servlet中设置多个内容类型,java,servlets,Java,Servlets,我有.pdf、.jpg、.docx文件,我想在单击按钮时打开它们。是否有任何方法可以在servlet中设置多个内容类型。我的servlet代码如下 String Docpath=request.getParameter("document"); String docname=request.getParameter("docName"); response.setContentType("application/pdf"); response.setHeader("Content-Dispos
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();
}
这是工作代码
File file=new File("T:\\Temp\\"+docname);
Path filePath=Paths.get("T:\\Temp\\"+docname);
response.setContentType(Files.probeContentType(filePath));
不能设置多个内容类型。您需要做的是确定从磁盘加载的文件的内容类型:
File file=new File("T:\\Temp\\"+docname);
找到内容类型后,请设置它:
response.setContentType(contentTypeOfTheFileIJustLoaded);
有几个选项可以帮助您找到文件的内容类型。请看以下问题:
您不能设置多个内容类型。您需要做的是确定从磁盘加载的文件的内容类型:
File file=new File("T:\\Temp\\"+docname);
找到内容类型后,请设置它:
response.setContentType(contentTypeOfTheFileIJustLoaded);
有几个选项可以帮助您找到文件的内容类型。请看以下问题:
可能只有一种MIME类型,可以是pdf、文本或任何其他格式。是否要在响应中发送多个文件?在这种情况下,您宁愿压缩文件。它可能只有一种MIME类型,可以是pdf或文本或任何其他格式。是否要在响应中发送多个文件?在这种情况下,您更愿意压缩文件。是的,它与
文件一起工作。probeContentType(path)
。谢谢您的建议。是的,它适用于文件。probeContentType(路径)
。谢谢你的建议。