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.pswp.cn/news/280420.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280420.shtml
英文地址,請注明出處:http://en.pswp.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 …