response.setHeader("Content-Type", "image/png");怎么改成公共的
时间: 2023-07-02 13:06:07 浏览: 58
可以将该代码放在一个公共的函数中,如下所示:
```java
public void setContentType(HttpServletResponse response, String contentType) {
response.setHeader("Content-Type", contentType);
}
```
然后在需要设置 Content-Type 的地方,调用该函数即可:
```java
setContentType(response, "image/png");
```
这样就可以避免重复代码,并且方便维护。
相关问题
Map type of resource to appropriate MIME type and use it to set Content-Type header in HTTP response
Here are some commonly used resource types and their corresponding MIME types:
- Text files: text/plain
- HTML files: text/html
- CSS files: text/css
- JavaScript files: application/javascript
- JSON files: application/json
- XML files: application/xml
- Images (JPEG, PNG, etc.): image/jpeg, image/png, etc.
- Audio files (MP3, WAV, etc.): audio/mpeg, audio/wav, etc.
- Video files (MP4, AVI, etc.): video/mp4, video/avi, etc.
To set the Content-Type header in an HTTP response, you can use the setHeader() method of the response object in your server-side code. For example, if you want to set the Content-Type to "text/html" for an HTML file, you can do the following in Node.js:
```
response.setHeader('Content-Type', 'text/html');
```
Or if you are using Express.js, you can use the following:
```
response.type('html');
```
通过springboot访问本地静态图片失败 Read Blocking (CORB) 已屏蔽 MIME 类型
出现这种情况可能是因为浏览器的安全策略导致的,可以尝试在代码中设置相关的响应头信息来解决。
可以在控制器方法中添加如下代码:
```java
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
```
其中,`Access-Control-Allow-Origin`用于设置允许跨域访问的域名,`Access-Control-Allow-Methods`用于设置允许的请求方法,`Access-Control-Allow-Headers`用于设置允许的请求头信息。
如果仍然不能解决问题,可能需要检查一下图片的 MIME 类型是否正确,在 HTML 中引用图片时,可以添加`type`属性来指定 MIME 类型,例如:
```html
<img src="path/to/image.png" type="image/png">
```
确保 MIME 类型和图片实际类型一致。