SpringMVC實(shí)現(xiàn)上傳下載文件
本文實(shí)例為大家分享了SpringMVC實(shí)現(xiàn)上傳下載文件的具體代碼,供大家參考,具體內(nèi)容如下
一、SpringMVC專門提供了CommonsMultipartResolver組件用于文件上傳:
(1)maxUploadSize 文件最大限制,單位是byte
(2)maxInMemorySize 低于這個(gè)大小的文件暫存內(nèi)存中
(3)defaultEncoding 默認(rèn)編碼utf-8
必須在spring-mvc.xml文件
<!-- (2)配置 MultipartResolver 實(shí)現(xiàn)文件上傳 ? ?? ? ? ? ? ? ? ? ?注意:id="multipartResolver"是固定寫法 ?? ? ? --> ?? ? ? <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> ?? ? ? ? <!-- 字符編碼 --> ?? ? ? ?<property name="defaultEncoding" value="utf-8"/> ?? ? ? ?<!-- max size 10M --> ?? ? ? ?<property name="maxUploadSize" value="10485760000"/> ?? ? ? ?<!--內(nèi)存中最大 4K ?--> ?? ? ? ?<property name="maxInMemorySize" value="4096"/> ?? ? ? </bean>
二、SpringMVC文件上傳引入jar包

必須在配置Pom.xml文件
<!-- fileupload start --> ?? ??? ?<dependency> ?? ??? ??? ?<groupId>commons-fileupload</groupId> ?? ??? ??? ?<artifactId>commons-fileupload</artifactId> ?? ??? ??? ?<version>1.3.1</version> ?? ??? ?</dependency> ? ?? ??? ?<dependency> ?? ??? ??? ?<groupId>commons-io</groupId> ?? ??? ??? ?<artifactId>commons-io</artifactId> ?? ??? ??? ?<version>2.4</version> ?? ??? ?</dependency> ? ?? ??? ?<!-- end -->
三、實(shí)現(xiàn)【單個(gè)文件】上傳
(1)JSP頁面必須放在WEB-INF下 upload1.jsp 必須添加enctype="multipart/form-data"
<body> ?? ?<div style="margin: 0 auto; margin-top: 100px; background:snow"> ?? ??? ?<form method="post" action="upload1.html" name="form1" ?? ??? ??? ?enctype="multipart/form-data"> ?? ??? ??? ?<p> ?? ??? ??? ??? ? ?照片:<input type="file" name="imagefile"> ?? ??? ??? ??? ?<input type="submit" value="上傳" name="button1"> <br> ?? ??? ??? ?</p> ?? ??? ?</form> ?? ?</div>
(2) 寫控制類 UploadController.java
@Controller
public class UploadController {
?
?? ?@RequestMapping("upload1")
?? ?public String getUpload(@RequestParam("imagefile") MultipartFile imagefile,
?? ??? ??? ?HttpServletRequest request) {
?? ??? ?// 獲取上傳的服務(wù)器路徑
?? ??? ?String pathString = request.getSession().getServletContext().getRealPath("/upload/");
?? ??? ?// 獲取文件
?? ??? ?String fileName = imagefile.getOriginalFilename();
?? ??? ?
?? ??? ?System.out.println(fileName);
?
?? ??? ?// 判斷上傳的路徑是否存在
?? ??? ?File file = new File(pathString);
?? ??? ?if (!file.exists()) {
?? ??? ??? ?file.mkdirs();
?? ??? ?}
?
?? ??? ?System.out.println("上傳路徑=" + pathString +"/"+ fileName);
?? ??? ?// 文件不存在
?? ??? ?File targetFile = new File(pathString +"/"+ fileName);
?? ??? ?if (!targetFile.exists()) {
?? ??? ??? ?try {
?? ??? ??? ??? ?targetFile.createNewFile();
?? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?
?? ??? ?try {
?? ??? ??? ?// 上傳
?? ??? ??? ?imagefile.transferTo(targetFile);
?? ??? ?} catch (IllegalStateException e) {
?? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ?e.printStackTrace();
?? ??? ?} catch (IOException e) {
?? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?
?? ??? ?//注意:/springmvc5/WEB-INF/jsp/http:/localhost:8888/springmvc5/upload/1.gif.jsp
?? ??? ?//返回文件,必須是重定向文件
?? ??? ?return "redirect:http://localhost:8888/springmvc5/upload/" + fileName;
?
?? ?} }(3)效果

選擇圖片路徑:

單擊上傳:

四、實(shí)現(xiàn)【多個(gè)文件】上傳
(1)JSP頁面(必須放在WEB-INF下) upload2.jsp 必須添加enctype="multipart/form-data"
<body> ?? ?<div style="margin: 0 auto; margin-top: 100px; background:snow"> ?? ??? ?<form method="post" action="upload2.html" name="form1" ?? ??? ??? ?enctype="multipart/form-data"> ?? ??? ??? ?<p> ?? ??? ??? ??? ? ?照片1:<input type="file" name="imagefile1"><p/> ?? ??? ??? ??? ? ?照片2:<input type="file" name="imagefile2"><p/> ?? ??? ??? ??? ?<input type="submit" value="上傳" name="button1"> <br> ?? ??? ??? ?</p> ?? ??? ?</form> ?? ?</div> </body>
(2) 寫控制類 UploadController.java
@RequestMapping("upload2")
?? ?public String getUpload2(HttpServletRequest request) {
?
?? ??? ?// 多文件上傳
?? ??? ?MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
?? ??? ?// 獲得多個(gè)文件
?? ??? ?Map<String, MultipartFile> map = multipartRequest.getFileMap();
?
?? ??? ?// 獲取上傳的服務(wù)器路徑
?? ??? ?String pathString = request.getSession().getServletContext().getRealPath("/upload/");
?? ??? ?// 判斷上傳的路徑是否存在
?? ??? ?File file1 = new File(pathString);
?? ??? ?if (!file1.exists()) {
?? ??? ??? ?file1.mkdirs();
?? ??? ?}
?
?? ??? ?// 獲取文件
?? ??? ?List<String> list = new ArrayList<String>();
?
?? ??? ?// 遍歷數(shù)據(jù)
?? ??? ?for (MultipartFile file : map.values()) {
?? ??? ??? ?String fileName = file.getOriginalFilename();
?? ??? ??? ?System.out.println("上傳路徑=" + pathString +"/"+ fileName);
?? ??? ??? ?// 文件不存在
?? ??? ??? ?File targetFile = new File(pathString ?+"/"+ fileName);
?? ??? ??? ?if (!targetFile.exists()) {
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?targetFile.createNewFile();
?? ??? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ?}
?
?? ??? ??? ?try {
?? ??? ??? ??? ?// 上傳
?? ??? ??? ??? ?file.transferTo(targetFile);
?
?? ??? ??? ??? ?// 保存路徑
?? ??? ??? ??? ?list.add("http://localhost:8888/springmvc5/upload/" + fileName);
?? ??? ??? ?} catch (IllegalStateException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?
?? ??? ?}
?? ??? ?// 保存每個(gè)上傳的路徑
?? ??? ?request.setAttribute("files", list);
?? ??? ?
?? ??? ?return "showUpload"; ? //跳轉(zhuǎn)到showUpload.jsp頁面哦!
?
?? ?}注意:return "showUpload";是具體顯示的頁面;必須配置視圖解析器在spring-mvc.xml文件中
<!--(1) spring 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" ?p:suffix=".jsp"></bean>
(3)JSP頁面: showUpload.jsp
<div style="margin: 0 auto; margin-top: 100px; background:snow">
?? ? ?<%
?? ? ? ?List<String> list =(List<String>) request.getAttribute("files");
?? ? ? ?
?? ? ? ?for(String str:list){
?? ? ?
?? ? ? %>
?? ? ? ? ?<a href="<%=str%>" rel="external nofollow" ><img src="<%=str%>" alt=""/></a>
?? ? ??
?? ? ? <%} %>
</div>(4)效果

單擊上傳:

查看上傳到服務(wù)器的圖片

五、下載圖片
(1)JSP頁面 login.jsp
<a href="download.html?fileName=08.gif" >下載圖片</a><p/>
(2)控制類DownController
@Controller
public class DownController {
?
?? ?@RequestMapping("/download")
?? ?public String download(@RequestParam String fileName,
?? ??? ??? ?HttpServletRequest request, HttpServletResponse response) {
?
?? ??? ?// 設(shè)置響應(yīng)編碼
?? ??? ?response.setContentType("text/html;charset=utf-8");
?
?? ??? ?// 設(shè)置請(qǐng)求編碼
?? ??? ?try {
?? ??? ??? ?request.setCharacterEncoding("utf-8");
?? ??? ?} catch (UnsupportedEncodingException e) {
?? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?
?? ??? ?// 字節(jié)流
?? ??? ?BufferedInputStream bis=null;
?? ??? ?BufferedOutputStream bos=null;
?
?? ??? ?// 獲取服務(wù)器的路徑
?? ??? ?String path = request.getSession().getServletContext().getRealPath("/upload/");
?
?? ??? ?// 下載的路徑
?? ??? ?String downPath = path +"/"+ fileName;
?
?? ??? ?try {
?? ??? ??? ?// 文件大小
?? ??? ??? ?long fileSize = new File(downPath).length();
?? ??? ??? ?
?? ??? ??? ?//設(shè)置內(nèi)容類型
?? ??? ??? ?response.setContentType("application/x-msdownload");
?? ??? ??? ?//設(shè)置頭信息
?? ??? ??? ?response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("utf-8"),"ISO8859-1"));
?? ??? ??? ?response.setHeader("Content-Length",String.valueOf(fileSize));
?? ??? ??? ?//字節(jié)流
?? ??? ??? ?bis = new BufferedInputStream(new FileInputStream(downPath));
?? ??? ??? ?bos= new BufferedOutputStream(response.getOutputStream());
?? ??? ??? ?//字節(jié)數(shù)組
?? ??? ??? ?byte[] by = new byte[2048];
?? ??? ??? ?
?? ??? ??? ?//
?? ??? ??? ?int length=0;
?? ??? ??? ?
?? ??? ??? ?//讀取
?? ??? ??? ?while((length=bis.read(by,0,by.length))!=-1){
?? ??? ??? ??? ?//寫入
?? ??? ??? ??? ?bos.write(by, 0, length);
?? ??? ??? ??? ?
?? ??? ??? ?}
?? ??? ??? ?
?? ??? ?} catch (Exception e) {
?? ??? ??? ?// TODO: handle exception
?? ??? ??? ?e.printStackTrace();
?? ??? ?}finally{
?? ??? ??? ?//關(guān)閉連接
?? ??? ??? ? if(bis!=null){
?? ??? ??? ??? ? try {
?? ??? ??? ??? ??? ?bis.close();
?? ??? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ? }
?? ??? ??? ? if(bos!=null){
?? ??? ??? ??? ? try {
?? ??? ??? ??? ??? ? bos.close();
?? ??? ??? ??? ? } catch (IOException e) {
?? ??? ??? ??? ??? ? // TODO Auto-generated catch block
?? ??? ??? ??? ??? ? e.printStackTrace();
?? ??? ??? ??? ? }
?? ??? ??? ? }
?? ??? ?}
?
?? ??? ?return null;
?
?? ?}
}(3)效果

保存或打開如下:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringMVC+Ajax實(shí)現(xiàn)文件批量上傳和下載功能實(shí)例代碼
- MyBatis與SpringMVC相結(jié)合實(shí)現(xiàn)文件上傳、下載功能
- SpringMVC實(shí)現(xiàn)文件的上傳和下載實(shí)例代碼
- springMVC配置環(huán)境實(shí)現(xiàn)文件上傳和下載
- 在SpringMVC框架下實(shí)現(xiàn)文件的上傳和下載示例
- SpringMVC下實(shí)現(xiàn)Excel文件上傳下載
- SpringMVC框架實(shí)現(xiàn)圖片上傳與下載
- SpringMVC實(shí)現(xiàn)文件上傳和下載功能
- SpringMVC實(shí)現(xiàn)文件上傳和下載的工具類
- SpringMvc3+extjs4實(shí)現(xiàn)上傳與下載功能
相關(guān)文章
java解決單緩沖生產(chǎn)者消費(fèi)者問題示例
這篇文章主要介紹了java解單緩沖生產(chǎn)者消費(fèi)者問題示例,需要的朋友可以參考下2014-04-04
SpringBoot實(shí)現(xiàn)自定義事件的方法詳解
這篇文章將用實(shí)例來和大家介紹一下如何在SpringBoot中自定義事件來使用觀察者模式。文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)SpringBoot有一定的幫助,需要的可以參考一下2022-06-06
詳解Java弱引用(WeakReference)的理解與使用
這篇文章主要介紹了Java弱引用(WeakReference)的理解與使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Java調(diào)用第三方http接口的四種方式總結(jié)
這篇文章主要給大家介紹了關(guān)于Java調(diào)用第三方http接口的四種方式,在實(shí)際開發(fā)中我們經(jīng)常會(huì)與第三方公司進(jìn)行合作,接入第三方接口,文中給出了詳細(xì)的代碼實(shí)例,需要的朋友可以參考下2023-08-08
spring boot整合scurity做簡(jiǎn)單的登錄校驗(yàn)的實(shí)現(xiàn)
這篇文章主要介紹了spring boot整合scurity做簡(jiǎn)單的登錄校驗(yàn)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04

