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地址:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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