Spring MVC实现文件下载

方法一:

    @RequestMapping("/testHttpMessageDown")public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {File file = new File(request.getSession().getServletContext().getClassLoader().getResource("test.xlsx").getPath());byte[] body = null;InputStream is = new FileInputStream(file);body = new byte[is.available()];is.read(body);HttpHeaders headers = new HttpHeaders();headers.add("Content-Disposition", "attchement;filename=" + file.getName());HttpStatus statusCode = HttpStatus.OK;ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);return entity;}

方法二:

    /** Download a file from *   - inside project, located in resources folder.*   - outside project, located in File system somewhere. */@RequestMapping(value="/download", method = RequestMethod.GET)public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {File file = new File(request.getSession().getServletContext().getClassLoader().getResource("test.xlsx").getPath());if(!file.exists()){String errorMessage = "Sorry. The file you are looking for does not exist";System.out.println(errorMessage);OutputStream outputStream = response.getOutputStream();outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));outputStream.close();return;}String mimeType= URLConnection.guessContentTypeFromName(file.getName());if(mimeType==null){System.out.println("mimetype is not detectable, will take default");mimeType = "application/octet-stream";}System.out.println("mimetype : "+mimeType);response.setContentType(mimeType);/* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\""));/* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*///response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        response.setContentLength((int)file.length());InputStream inputStream = new BufferedInputStream(new FileInputStream(file));//Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());}

Maven示例:

https://github.com/easonjim/5_java_example/tree/master/springmvc/test1

 

参考:

http://www.yiibai.com/spring_mvc/spring-mvc-4-file-download-example.html

http://blog.csdn.net/wuzuodingfeng/article/details/53489089

==>如有问题,请联系我:easonjim#163.com,或者下方发表评论。<==

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280420.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[MobX State Tree数据组件化开发][3]:选择正确的types.xxx

?系列文章目录? 定义Model时&#xff0c;需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍&#xff0c;方便同学们在定义props时挑选正确的类型。 前提 定义props之前&#xff0c;有一个前提是&#xff0c;你已经明确地知道这…

ubuntu系统备份和还原_如何使用Aptik在Ubuntu中备份和还原您的应用程序和PPA

ubuntu系统备份和还原If you need to reinstall Ubuntu or if you just want to install a new version from scratch, wouldn’t it be useful to have an easy way to reinstall all your apps and settings? You can easily accomplish this using a free tool called Apti…

rest_framework09:自动生成接口文档(简略)

coreapi 参考 python/Django-rest-framework框架/8-drf-自动生成接口文档 | Justin-刘清政的博客 Swagger 很多语言都支持&#xff0c;看起来用的人多。 参考fastapi的界面

AppDomainManager后门的实现思路

本文讲的是AppDomainManager后门的实现思路&#xff0c;0x00 前言从Casey SmithsubTee学到的一个技巧&#xff1a;针对.Net程序&#xff0c;通过修改AppDomainManager能够劫持.Net程序的启动过程。 如果劫持了系统常见.Net程序如powershell.exe的启动过程&#xff0c;向其添加…

所有内耗,都有解药。

你是否常常会有这种感觉&#xff1a;刚开始接手一件事情&#xff0c;脑海中已经幻想出无数个会发生的问题&#xff0c;心里也已笃定自己做不好&#xff1b;即使别人不经意的一句话&#xff0c;也会浮想一番&#xff0c;最终陷入自我怀疑&#xff1b;随便看到点什么&#xff0c;…

ABAP 通过sumbit调用另外一个程序使用job形式执行-简单例子

涉及到两个程序&#xff1a; ZTEST_ZUMA02 (主程序)ZTEST_ZUMA(被调用的程序&#xff0c;需要以后台job执行)"ztest_zuma 的代码DATA col TYPE i VALUE 0.DO 8 TIMES.MESSAGE JOB HERE TYPE S.ENDDO.程序ZTEST_ZUMA是在程序ZTEST_ZUMA02中以job的形式调用的&#xff0c;先…

那些影响深远的弯路

静儿最近反思很多事情&#xff0c;不仅是当时做错了。错误定式形成的思维习惯对自己的影响比事情本身要大的多。经常看到周围的同事&#xff0c;非常的羡慕。他们都很聪明、有自己的方法。就算有些同事工作经验相对少一些&#xff0c;但是就像在废墟上创建一个辉煌的城市要比在…

如何使用APTonCD备份和还原已安装的Ubuntu软件包

APTonCD is an easy way to back up your installed packages to a disc or ISO image. You can quickly restore the packages on another Ubuntu system without downloading anything. APTonCD是将安装的软件包备份到光盘或ISO映像的简便方法。 您可以在不下载任何东西的情况…

rest_framework10:base64补充/修改头像

base64补充 # base64 变长&#xff0c;可反解 # md5 固定长度&#xff0c;不可反解# base64 编码和解码 import base64 import json dic{name:test,age:18} dic_strjson.dumps(dic)retbase64.b64encode(dic_str.encode(utf-8)) print(ret)# 解码 ret2base64.b64decode(ret) pri…

next_permutation(全排列算法)

next_permutation(全排列算法) STL提供了两个用来计算排列组合关系的算法&#xff0c;分别是next_permutation和prev_permutation。 首先解释下全排列&#xff0c;顾名思义&#xff0c;即一组数的全部排列的情况。 next_permutation 即列出一组数的全部排列情况&#xff0c;不过…

C#自定义字符串压缩和解压缩源码库

如下的内容是关于C#自定义字符串压缩和解压缩库的内容。class ZipLib{public static string Zip(string value){byte[] byteArray new byte[value.Length];int indexBA 0;foreach (char item in value.ToCharArray()){byteArray[indexBA] (byte)item;}System.IO.MemoryStrea…

使用 Visual Studio 2022 调试Dapr 应用程序

使用Dapr 编写的是一个多进程的程序, 两个进程之间依赖于启动顺序来组成父子进程&#xff0c;使用Visual Studio 调试起来可能会比较困难&#xff0c;因为 Visual Studio 默认只会把你当前设置的启动项目的启动调试。好在有Visual Studio 扩展&#xff08;Microsoft Child Proc…

卸载 cube ui_如何还原Windows 8附带的已卸载现代UI应用程序

卸载 cube uiWindows 8 ships with built-in apps available on the Modern UI screen (formerly the Metro or Start screen), such as Mail, Calendar, Photos, Music, Maps, and Weather. Installing additional Modern UI apps is easy using the Windows Store, and unins…

rest_framework11:jwt简单例子/自定制基于jwt认证类

jwt简单例子 一、登陆设置 1.不需要写login的视图类&#xff0c;使用jwt内置的。 2.需要前置条件&#xff0c;已有继承AbstractUser models,并且有数据&#xff0c;用于校验&#xff0c;返回token。 urls.py from rest_framework_jwt.views import obtain_jwt_tokenurlpat…

Java各种数据类型,自己学习写的笔记!!!

java编程规范&#xff1a; 1.良好的标识符的命名保留字不能作为标识符命名&#xff1a; class、public、static..., goto,const区分大小写&#xff1a;helloWorld、HelloWorld 2.良好的注释习惯 3.良好的缩进&#xff1a;没遇到一个代码块缩进一次&#xff08;一个tab键&…

Java Decompiler(Java反编译工具)

Java Decompiler官网地址&#xff1a;http://jd.benow.ca/ 官网介绍&#xff1a; The “Java Decompiler project” aims to develop tools in order to decompile and analyze Java 5 “byte code” and the later versions. JD-Core is a library that reconstructs Java sou…

20位程序员关于求职的疑问,以及我给出的参考答案

作者&#xff1a;陆小凤首发&#xff1a;公众号【程序员江湖】阅读本文大概需要 6 分钟。前几天发了一条朋友圈对于求职小伙伴们提出的问题&#xff0c;我进行了收集整理&#xff0c;统一反馈。也许这20个问题也是你们遇到的问题&#xff0c;所以趁着年前赶紧把它发出来。以下2…

MassTransit | 基于MassTransit Courier 实现 Saga 编排式分布式事务

Saga 模式Saga 最初出现在1987年Hector Garcaa-Molrna & Kenneth Salem发表的一篇名为《Sagas》的论文里。其核心思想是将长事务拆分为多个短事务&#xff0c;借助Saga事务协调器的协调&#xff0c;来保证要么所有操作都成功完成&#xff0c;要么运行相应的补偿事务以撤消先…

ccleaner无法更新_CCleaner正在静默更新关闭自动更新的用户

ccleaner无法更新CCleaner is forcing updates on users who specifically opt out of automatic updates. Users will only find out about these unwanted updates when they check the version number. CCleaner强制对专门选择退出自动更新的用户进行更新。 用户只有在检查版…

查找域内所有的Windows Server 2012 R2的服务器,并区分出哪些是物理机,那些是虚拟机...

通过使用Get-Adcomputer和Get-Wmiobject 组合来实现。思路是这样的&#xff0c;先看一台服务器的属性值有什么可用利用的。[12r2-dc]: PS C:\> Get-ADComputer -Identity 12r2-dc -Properties *AccountExpirationDate :accountExpires …