写出一个Springmvc的文件下载的案例
下面是一个Spring MVC的文件下载案例:
- 创建一个控制器类 FileDownloadController.java:
@Controller
public class FileDownloadController {
@RequestMapping("/download")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = "D:/files/file.txt"; // 文件路径
File file = new File(filePath);
if (file.exists()) {
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
// 创建输入流,读取文件内容
InputStream inputStream = new FileInputStream(file);
// 创建输出流,写入响应
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
// 关闭流
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
}
- 在Spring MVC的配置文件中配置视图解析器和请求映射:
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置请求映射 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.example.controller" />
- 创建一个 JSP 文件 download.jsp 用于触发文件下载:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Download Example</title>
</head>
<body>
<h1>File Download Example</h1>
<form action="${pageContext.request.contextPath}/download" method="GET">
<input type="submit" value="Download File">
</form>
</body>
</html>
- 创建一个启动类 MainApp.java:
public class MainApp {
public static void main(String[] args) {
SpringApplication.run(MainApp.class, args);
}
}
- 启动应用并访问 http://localhost:8080/download,点击 "Download File" 按钮即可下载文件
原文地址: http://www.cveoy.top/t/topic/iTfh 著作权归作者所有。请勿转载和采集!