下面是一个 Spring MVC 的文件下载案例,展示了如何使用 Spring MVC 实现文件下载功能。

  1. 创建一个控制器类 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();
        }
    }
}
  1. 在 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" />
  1. 创建一个 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>
  1. 创建一个启动类 MainApp.java
public class MainApp {
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}
  1. 启动应用并访问 http://localhost:8080/download,点击 'Download File' 按钮即可下载文件。

注意:

  • 请将 D:/files/file.txt 替换为您的实际文件路径。
  • 确保您已经配置了 Spring MVC 的环境。
  • 此示例仅展示了基本的下载功能,您可以根据需要进行扩展和优化。
Spring MVC 文件下载案例:完整步骤和代码示例

原文地址: https://www.cveoy.top/t/topic/qzeX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录