SpringMVC實現(xiàn)文件上傳和下載功能
本文實例為大家分享了SpringMVC實現(xiàn)文件上傳和下載的具體代碼,供大家參考,具體內容如下
文件上傳
第一步,加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
第二步,在SpringMVC配置文件中配置CommonsMultipartResovler
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> //最大上傳文件大小 <property name="maxUploadSize" value="1048576"></property> </bean>
第三步,前端表單 注意 【POST請求,file類型,enctype="multipart/form-data"】
<form action="${pageContext.request.contextPath }/testUpload" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"><br> desc:<input type="text" name="desc"><br> <input type="submit" value="submit"><br> </form><br>
第四步,在controller層創(chuàng)建方法
@RequestMapping(value="/testUpload",method=RequestMethod.POST) private String testUpload(HttpServletRequest request,@RequestParam(value="desc")String desc,@RequestParam(value="file") CommonsMultipartFile file) { InputStream inputStream = null; OutputStream outputStream = null; ServletContext servletContext = request.getServletContext(); //獲取文件存放的真實路徑 String realPath = servletContext.getRealPath("/upload"); //為了避免多次上傳同一個文件導致命名重復,在文件名前加UUID前綴 String prefix=UUID.randomUUID().toString(); prefix=prefix.replace("-", ""); String fileName=prefix+"_"+file.getOriginalFilename(); File file2=new File(realPath); //檢查文件目錄是否存在,若不存在就創(chuàng)建目錄 if(!file2.exists()){ file2.mkdirs(); } try { inputStream=file.getInputStream(); outputStream=new FileOutputStream(new File(realPath+"/"+fileName)); //設置緩沖區(qū) byte[]buffer=new byte[1024]; int len=0; //循環(huán)檢測文件是否上傳完成,未完成就向寫入輸出流 while((len=inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, len); outputStream.flush(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ //關閉輸入輸出流 if(outputStream !=null){ try { outputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return "success"; }
文件下載
用ResponseEntity<byte[]> 返回值完成文件下載;在jsp頁面給出鏈接即可。
jsp頁面鏈接地址:
在controller層創(chuàng)建方法
@RequestMapping(value="/testResponseEntity") ResponseEntity<byte[]>testResponseEntity(HttpServletRequest request)throws Exception{ ServletContext servletContext = request.getServletContext(); //獲取要下載的文件的文件名 String fileName="喜劇之王.mp3"; //獲取要下載的文件的真實路徑 String realPath = servletContext.getRealPath("/WEB-INF/"+fileName); //創(chuàng)建輸入流 InputStream inputStream=new FileInputStream(new File(realPath)); byte[]body=new byte[inputStream.available()]; inputStream.read(body); MultiValueMap<String, String>headers=new HttpHeaders(); //設置頭信息和字符集 fileName = new String(fileName.getBytes("gbk"),"iso8859-1"); headers.set("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]>responseEntity =new ResponseEntity<byte[]>(body, headers, statusCode); return responseEntity; }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
java 方法重寫與權限修飾符以及多態(tài)和抽象類詳解概念和用法
重寫是子類對父類的允許訪問的方法的實現(xiàn)過程進行重新編寫, 返回值和形參都不能改變。即外殼不變,核心重寫,權限修飾符用于控制被修飾變量、方法、類的可見范圍,說明了面向對象的封裝性,所以我們要適用他們盡可能的讓權限降到最低,從而安全性提高2021-10-10SpringBoot2.1.x,創(chuàng)建自己的spring-boot-starter自動配置模塊操作
這篇文章主要介紹了SpringBoot2.1.x,創(chuàng)建自己的spring-boot-starter自動配置模塊操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Spring Boot Web應用開發(fā) CORS 跨域請求支持
本篇文章主要介紹了Spring Boot Web應用開發(fā) CORS 跨域請求支持,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05解決SpringBoot項目中l(wèi)og4j與logback的Jar包沖突問題
這篇文章主要給大家介紹了解決SpringBoot項目中l(wèi)og4j與logback的Jar包沖突問題,文中有詳細的解決方法和沖突的原因,有遇到相同問題的朋友可以參考閱讀本文2023-10-10Java Spring MVC獲取請求數(shù)據(jù)詳解操作
Spring MVC 是 Spring 提供的一個基于 MVC 設計模式的輕量級 Web 開發(fā)框架,本質上相當于 Servlet,Spring MVC 角色劃分清晰,分工明細。由于 Spring MVC 本身就是 Spring 框架的一部分,可以說和 Spring 框架是無縫集成2021-11-11