MIME 类型
response.setContentType 设置的是响应的 MIME 类型(或媒体类型),它告诉客户端(如浏览器)如何处理返回的数据。不同的 MIME 类型表示不同类型的内容,常见的 MIME 类型包括文本、图像、音频、视频等。
常见的 MIME 类型
-
文本类型
text/plain:纯文本text/html:HTML文档text/css:CSS样式表text/javascript:JavaScript代码
-
应用类型
application/json:JSON数据application/xml:XML数据application/pdf:PDF文档application/octet-stream:任意的二进制数据(通常用于文件下载)application/zip:ZIP压缩文件application/msword:Microsoft Word文档application/vnd.ms-excel:Microsoft Excel文档
-
图像类型
image/jpeg:JPEG图像image/png:PNG图像image/gif:GIF图像image/svg+xml:SVG图像
-
音频/视频类型
audio/mpeg:MPEG音频audio/ogg:OGG音频video/mp4:MP4视频video/webm:WebM视频
-
多部分类型
multipart/form-data:表单数据,通常用于文件上传
示例:设置不同的内容类型
以下是一些示例代码,展示如何设置不同的 MIME 类型:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class ContentTypeController {
@GetMapping("/text")
public void returnText(HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
response.getWriter().write("This is plain text.");
}
@GetMapping("/json")
public void returnJson(HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.getWriter().write("{\"key\":\"value\"}");
}
@GetMapping("/html")
public void returnHtml(HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.getWriter().write("<html><body><h1>This is HTML</h1></body></html>");
}
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
byte[] fileContent = "This is a file".getBytes();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"file.txt\"");
response.setContentLength(fileContent.length);
response.getOutputStream().write(fileContent);
response.getOutputStream().flush();
}
}
总结
response.setContentType 的作用是设置响应的 MIME 类型,使客户端知道如何处理响应的数据。根据具体的需求,选择合适的 MIME 类型,以确保客户端正确处理响应内容。

浙公网安备 33010602011771号