参考 :?
????????Servlet之文件预览_httpservletresponse 设置文件预览-CSDN博客?
????????java如何获取文件的媒体类型(MIME类型)? - Java中文网?
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Controller
public class YuLangController {
@RequestMapping("/yl/{fileName}")
public void yl(@PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mimeType = mimeTypesMap.getContentType(fileName);
// 获取文件的媒体类型
response.setContentType(mimeType);
// 输出文件 fileName为相对路径 fileName= [System.getProperty("user.dir")+File.separator+fileName]
InputStream is = new FileInputStream(fileName);
OutputStream os = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
// 关闭流
bos.flush();
bos.close();
is.close();
}
}