HTTP消息头之Content-Type
Content-Type(MediaType),即是Internet Media Type,互联网媒体类型,也叫做MIME类型。
在互联网中有成百上千中不同的数据类型,HTTP在传输数据对象时会为他们打上称为MIME的数据格式标签,用于区分数据类型。最初MIME是用于电子邮件系统的,后来HTTP也采用了这一方案。
在HTTP协议消息头中,使用Content-Type来表示请求和响应中的媒体类型信息。它用来告诉服务端如何处理请求的数据,以及告诉客户端(一般是浏览器)如何解析响应的数据,比如显示图片,解析并展示html等等。
Content-Type的格式:
Content-Type:type/subtype ;parameter
type:主类型,任意的字符串,如text,如果是*号代表所有;
subtype:子类型,任意的字符串,如html,如果是*号代表所有,用“/”与主类型隔开;
parameter:可选参数,如charset,boundary等。
例如:
Content-Type: text/html;
Content-Type: application/json;charset:utf-8;
HTTP消息头之Content-Disposition
Content-Disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。当Internet Explorer接收到头时,他会激活文件下载
对话框,它的文件名框自动填充headers指定的文件名。
服务器向浏览器发送文件时,如果是浏览器支持的文件类型,一般会默认使用浏览器打开,比如txt
、jpg
等。如果需要提示用户保存,就要利用Content-Disposition
进行处理,关键在于一定要加上attachment
。
"Content-Disposition","attachment;filename=FileName.txt"
文件下载
import cn.hutool.core.io.file.FileNameUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
......
// http://localhost:8080/download?location=E://11047//Videos//1.mp4
// http://localhost:8080/download?location=E://11047//Document//1.pdf
@GetMapping("/download")
public void download(@RequestParam("location") String location, HttpServletResponse response) {
File file = new File(location);
if (file.exists() && file.isFile()) {
try (FileInputStream fileInputStream = new FileInputStream(file)) {
String filename = FileNameUtil.getName(location);
setResponseHeadersByFilename(filename, response);
IOUtils.copy(fileInputStream, response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public void setResponseHeadersByFilename(String filename, HttpServletResponse response) throws UnsupportedEncodingException {
MediaType mediaType = MediaTypeFactory.getMediaType(filename)
.orElse(MediaType.ALL);
response.setHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString());
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
String decodeFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + decodeFilename);
}
评论区