springboot文件下载
时间: 2023-05-28 10:01:35 浏览: 88
Spring Boot中文件下载可以通过以下步骤实现:
1. 通过Spring MVC配置一个处理器映射器和处理器适配器,处理文件下载请求。
```
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("~/files/");
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".html");
return resolver;
}
@Bean
public MappingJackson2HttpMessageConverter jsonConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS));
converter.setSupportedMediaTypes(MediaType.APPLICATION_JSON);
return converter;
}
@Bean
public HttpMessageConverters messageConverters() {
return new HttpMessageConverters(jsonConverter());
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("*")
.allowedOrigins("*");
}
}
```
2. 创建一个Controller类,并为文件下载请求提供一个映射路径。
```
@RestController
public class FileDownloadController {
private final static String BASE_PATH = "/files";
private final static String DEFAULT_FILE_NAME = "example.txt";
@GetMapping(BASE_PATH + "/{fileName:.+}")
public void downloadFile(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
String realPath = request.getServletContext().getRealPath("../" + BASE_PATH + "/" + fileName);
File file = new File(realPath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String mimeType = request.getServletContext().getMimeType(file.getAbsolutePath());
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
response.setContentLength((int) file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
@GetMapping(BASE_PATH)
public ResponseEntity<Resource> downloadDefaultFile(HttpServletRequest request) throws IOException {
String realPath = request.getServletContext().getRealPath("../" + BASE_PATH + "/" + DEFAULT_FILE_NAME);
Path path = Paths.get(realPath);
Resource resource = new UrlResource(path.toUri());
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + DEFAULT_FILE_NAME);
return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
}
}
```
3. 启动Spring Boot应用程序并测试文件下载功能。使用浏览器或命令行工具尝试下载文件。
阅读全文