web修煉-SpringMVC實現文件上傳下載等實例

添加上傳的Maven依賴

      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.2</version>
      </dependency>
      <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.5</version>
      </dependency>

在mvc配置文件中添加上傳文件的Bean

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--配置上傳文件-->
        <property name="defaultEncoding" value="utf-8"/><!--默認字符編碼-->
        <property name="maxUploadSize" value="10485760000"/><!--上傳文件大小-->
        <property name="maxInMemorySize" value="4096"/><!--內存中的緩存大小-->

    </bean>

創建單上傳的前端頁面

oneUpload.jsp

<%--
  Created by IntelliJ IDEA.
  User: elijahliu
  Date: 2017/2/24
  Time: 13:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>單文件上傳</title>
</head>
<body>
    <div style="margin: 100px auto 0;">
        <form action="/oneUpload" method="post" enctype="multipart/form-data"><%--定義enctype來用于文件上傳--%>
            <p>
                <span>文件</span>
                <input type="file" name="imageFile">
                <input type="submit">

            </p>

        </form>
    </div>

</body>
</html>

創建多上傳頁面
moreUpload.jsp

<%--
  Created by IntelliJ IDEA.
  User: elijahliu
  Date: 2017/2/24
  Time: 13:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>多文件上傳</title>
</head>
<body>
<div style="margin: 100px auto 0;">
    <form action="/moreUpload" method="post" enctype="multipart/form-data"><%--定義enctype來用于文件上傳--%>
        <p>
            <span>文件1</span>
            <input type="file" name="imageFile1">
        </p>
        <p>
            <span>文件2</span>
            <input type="file" name="imageFile2">
        </p>
        <p>
            <input type="submit">
        </p>



    </form>
</div>

</body>
</html>

編寫Controller層的代碼

UploadController.java

package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by elijahliu on 2017/2/24.
 */
@Controller
public class UploadController {
    @RequestMapping("/oneUpload")
    public String onUpload(@RequestParam("imageFile")MultipartFile imageFile, HttpServletRequest request) {//獲取文件參數
        String uploadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";//獲取路徑
        String filename = imageFile.getOriginalFilename();//獲取上傳文件的源文件名

        File dir = new File(uploadUrl);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        System.out.println("文件上傳到" + uploadUrl + filename);
        File targetFile = new File(uploadUrl + filename);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            imageFile.transferTo(targetFile); //這一句就是將上傳的文件轉化到剛才新建的文件中去了
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:http://localhost:8080/upload/"+filename;
    }


    @RequestMapping("/moreUpload")
    public String moreUpload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Map<String,MultipartFile> files = multipartHttpServletRequest.getFileMap();//獲取圖片的集合

        String uploadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";
        File dir = new File(uploadUrl);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        List<String> fileList = new ArrayList<String>();

        for (MultipartFile file:files.values()) {//使用循環??map集合上傳文件
            File targetFile = new File(uploadUrl + file.getOriginalFilename());
            if (!targetFile.exists()) {
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    file.transferTo(targetFile);
                    fileList.add("http://localhost:8080/upload/"+file.getOriginalFilename());//將文件路徑添加到文件列表中去
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        request.setAttribute("files",fileList);
        return "moreUploadResult";


    }

}

編寫多上傳的結果頁面

<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: elijahliu
  Date: 2017/2/24
  Time: 13:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>多文件上傳結果</title>
</head>
<body>
<div style="margin: 0 auto 100px">
    <%
        List<String> fileList = (List<String>) request.getAttribute("files");
        for (String url:fileList) {
    %>
    <a href="<%=url%>">
        <img alt="" src="<%=url%>"/>
    </a>
    <%
        }
    %>
</div>

</body>
</html>

創建下載Controller

package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by elijahliu on 2017/2/24.
 */
@Controller
public class DownloadController {

    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response){
        String fileName = "1.JPG";
        System.out.println(fileName);
        response.setContentType("text/html;charset=utf-8"); /*設定相應類型 編碼*/
        try {
            request.setCharacterEncoding("UTF-8");//設定請求字符編碼
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        java.io.BufferedInputStream bis = null;//創建輸入輸出流
        java.io.BufferedOutputStream bos = null;

        String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload/";//獲取文件真實路徑
        System.out.println(ctxPath);
        String downLoadPath = ctxPath + fileName;
        System.out.println(downLoadPath);
        try {
            long fileLength = new File(downLoadPath).length();//獲取文件長度
            response.setContentType("application/x-msdownload;");//下面這三行是固定形式
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));//創建輸入輸出流實例
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];//創建字節緩沖大小
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            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;

    }

}

創建導航頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>導航</title>
</head>
<body>
<div style="margin: 0 auto 100px;">
    <a href="topage.html?pagename=oneUpload">單文件上傳</a>
    <a href="topage.html?pagename=moreUpload">多文件上傳</a>
    <a href="http://localhost:8080/download">文件下載</a>
    <a href="topage.html?pagename=login">驗證碼</a>

</div>

</body>
</html>

GitHub地址:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,117評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,860評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,128評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,291評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,025評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,421評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,477評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,642評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,177評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,970評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,157評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,717評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,410評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,821評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,053評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,896評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,157評論 2 375

推薦閱讀更多精彩內容

  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,900評論 6 342
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,804評論 18 139
  • JAVA面試題 1、作用域public,private,protected,以及不寫時的區別答:區別如下:作用域 ...
    JA尐白閱讀 1,176評論 1 0
  • 叔本華說,“人總以為他所看到的便是這個世界的極限”。 思考,即對問題或爭議的解決為目的的一種積極主動的心理活動,其...
    M洋蔥閱讀 222評論 0 2