美文网首页
web修炼-SpringMVC实现文件上传下载等实例

web修炼-SpringMVC实现文件上传下载等实例

作者: 在南方的北方人_Elijah | 来源:发表于2017-02-24 16:14 被阅读2186次

添加上传的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地址:

相关文章

网友评论

      本文标题:web修炼-SpringMVC实现文件上传下载等实例

      本文链接:https://www.haomeiwen.com/subject/fqkwwttx.html