java HttpServletRequest:如何确定请求资产的内容类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3433844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:50:23  来源:igfitidea点击:

HttpServletRequest: How to determine Content-Type of requested asset

javajettycontent-typeservlets

提问by Richard H

I am writing a quick-and-dirty static file server using Jetty. I need to set the Content-Type for each response:

我正在使用 Jetty 编写一个快速而肮脏的静态文件服务器。我需要为每个响应设置 Content-Type:

HttpServletResponse.setContentType("content/type");

For a given file request, how do I reliably determine what content type to set? Is it a question of examining the file extension, or is there a more sophisticated method? (E.g what if there is no file extension, or the extension does not reflect the content type?)

对于给定的文件请求,我如何可靠地确定要设置的内容类型?是检查文件扩展名的问题,还是有更复杂的方法?(例如,如果没有文件扩展名,或者扩展名不反映内容类型怎么办?)

Thanks Richard

谢谢理查德

回答by Pablo Fernandez

Can't you just check the request header Content-Typeand set the response to that?

你不能只检查请求头Content-Type并设置响应吗?

I don't know the kind of clients you are planning to support but if they are browsers I guess you should be fine with that. If you control the clients, it's a good practice that they send you that header anyways.

我不知道您打算支持哪种客户端,但如果它们是浏览器,我想您应该可以接受。如果您控制客户端,那么他们无论如何都会向您发送该标头是一种很好的做法。

Good Luck!

祝你好运!

回答by jmort253

Since you're using the HttpServletResponse object in your question, I'm assuming you have the ServletContext available to you in your Controllers. I just solved this same problem just using methods available from the servletContext.

由于您在问题中使用了 HttpServletResponse 对象,因此我假设您的控制器中有 ServletContext 可用。我刚刚使用 servletContext 中可用的方法解决了同样的问题。

Since you're writing a file server, you can just pass in the path to the file in the getMimeType method of the ServletContext, and it should return the mimeType, if it can determine it.

由于您正在编写文件服务器,因此您可以在 ServletContext 的 getMimeType 方法中传入文件的路径,如果可以确定,它应该返回 mimeType。

String path = "/js/example.js";
String mimeType = getServletContext().getMimeType(path);
resp.setContentType(mimeType);   // HttpServletResponse object

NOTE: Sets the content type to "application-x/javascript" in this particular example.

注意:在此特定示例中将内容类型设置为“application-x/javascript”。

Additional information:I believe this solution also assumes your files are stored in a location accessible to the ServletContext. If not, then one of the other solutions may be best.

附加信息:我相信此解决方案还假定您的文件存储在 ServletContext 可访问的位置。如果没有,那么其他解决方案之一可能是最好的。

回答by YoK

You can use URLConnection.guessContentTypeFromStream

您可以使用URLConnection.guessContentTypeFromStream

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);