- @Controller
- public class DownloadController {
- @RequestMapping("download.htm")
- public void downloadFile(String fileName,HttpServletResponse response){
- response.setCharacterEncoding("utf-8");
- response.setContentType("multipart/form-data");
- response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
- try {
- File file=new File(fileName);
- System.out.println(file.getAbsolutePath());
- InputStream inputStream=new FileInputStream("file/"+file);
- OutputStream os=response.getOutputStream();
- byte[] b=new byte[1024];
- int length;
- while((length=inputStream.read(b))>0){
- os.write(b,0,length);
- }
- inputStream.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
本文介绍了一个使用Spring MVC实现的文件下载控制器的具体实现方法。该控制器通过@RequestMapping注解映射了/download.htm请求路径,能够接收文件名参数并返回指定文件。文章详细展示了如何设置HTTP响应头来触发文件下载,以及如何读取文件并将其发送到客户端。

被折叠的 条评论
为什么被折叠?



