基于ssm框架上传下载的实现

一、相关配置

框架应该已经搭建好了,所以这里不再复述。在ssm框架的基础上配置下面的内容。
1.pom.xml的配置

<properties>
   <commons-fileupload.version>1.3.1</commons-fileupload.version>
   <commons-io.version>2.4</commons-io.version>
</properties>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons-io.version}</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons-fileupload.version}</version>
      <exclusions>
        <exclusion>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

2.spring-mvc.xml中的配置

<!-- 定义文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880" />
        <property name="maxInMemorySize" value="4096" />
    </bean>

二、上传的实现

1.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传页面</title>
</head>
<body>
        <form method="post" action="file/upload" enctype="multipart/form-data">
            <p><span>文件:</span>
                <input type="file" name="file">
            </p>

            <p><input type="submit" value="提交"></p>
        </form>
</body>
</html>

代码:

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

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileUpload{
    @RequestMapping("/upload")
    public void upload(@RequestParam("file")MultipartFile file, HttpServletRequest request,
                         HttpServletResponse response, ModelMap model) throws Exception {
        //获取原始文件名
        String fileName=file.getOriginalFilename();
        System.out.println("原始文件名:"+fileName);
        //新文件
        String newfile= UUID.randomUUID()+fileName;
        //获取项目路径
        ServletContext context=request.getSession().getServletContext();
        //获取上传文件的保存目录,将上传的文件存放于WEB-INF目录下
        // 不允许外界直接访问,保证上传文件的安全
        String savePath=context.getRealPath("/WEB-INF/upload/");
        File files=new File(savePath);
        if(files.exists()&&files.isDirectory()){//若上传目录不存在,则创建目录
            files.mkdirs();
        }
        String message="";
        InputStream is=null;
        FileOutputStream fos=null;
        byte []buffer=new byte[100*1024];//根据上传文件大小设定
        try{
            is=file.getInputStream();// 获得上传文件流
            //创建文件输出流  使用FileOutputStream打开服务器端的上传文件
            fos=new FileOutputStream(savePath+newfile);
            int len=0;
            //开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
            //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
            while((len=is.read(buffer))>0){
                fos.write(buffer,0,len);//写入到指定的目录当中
            }
            fos.flush();
            is.close();
            fos.close();
            message="上传成功!"+ "<br>";
            message+="上传内容:" + newfile + "<br>";
            System.out.println("上传内容:" +newfile+ "<br>");
        } catch (IOException e) {
            message= "文件上传失败!";
            throw new Exception(e);
        }
        System.out.print("上传文件到:"+savePath+newfile);
        //设置消息 并跳转页面
        request.setAttribute("message",message);
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }
}

3.运行
这里写图片描述
这里写图片描述
这里写图片描述
查看后台内容
这里写图片描述
保存路径下查看
这里写图片描述
测试成功,上传功能就完成了。

三、文件下载

1.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
    <title>下载文件列表</title>
</head>

<body>
<!-- 判断下载列表里是否有内容 -->
<c:if test="${empty fileNameMap}">
    <c:redirect url="file/listFile"/>
</c:if>
<!-- 遍历Map集合 -->
<c:forEach var="me" items="${fileNameMap}" >
    <c:url value="http://localhost:8080/file/downFile" var="downurl">
        <c:param name="filename" value="${me.key}"></c:param>
    </c:url>
    ${me.value}<a href="${downurl}">下载</a>
    <br/>
</c:forEach>

</body>
</html>

2.文件列表代码

@Controller
@RequestMapping("/file")
public class FileList {
    @RequestMapping("/listFile")
    public void listFile(HttpServletRequest request, HttpServletResponse response)
            throws Exception{
        //获取文件的目录
        ServletContext context=request.getSession().getServletContext();
        System.out.println("下载文件目录:"+context);
        //下载位置
        String filePath=context.getRealPath("/WEB-INF/upload/");
        System.out.println("下载位置:"+filePath);
        //存储要下载的文件名
        Map<String,String> fileNameMap=new HashMap<String,String >();
        //递归遍历filepath目录下所有文件和目录,将文件的文件名存储到map集合中
        listfile(new File(filePath),fileNameMap);
        System.out.println(fileNameMap);
        //将Map集合发送到listFile.jsp页面进行显示
        request.setAttribute("fileNameMap",fileNameMap);
        request.getRequestDispatcher("/listFile.jsp").forward(request, response);
    }
    private void listfile(File file, Map<String, String> fileNameMap) {
        //若file代表不是一个文件而是一个目录
        if(!file.isFile()){
            //列出该目录下的所有文件和目录
            File files[]=file.listFiles();
            //遍历files[]数组
            for(File f:files){
                listfile(f,fileNameMap);
            }
        }else{
            //获取文件原始名称
            String realName=file.getName().substring(file.getName().indexOf(" ")+1);
            fileNameMap.put(file.getName(),realName);
        }
    }
}

3.下载块代码

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

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Controller
@RequestMapping("/file")
public class FileDownload {
    @RequestMapping("/downFile")
    public void downFile(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("text/html;charset=utf-8");
        //获取需要下载的文件名
        String fileName = request.getParameter("filename");
        System.out.println("下载的文件名:" + fileName);
        String message = "";
        try {
            fileName = new String(fileName.getBytes("iso8859-1"), "utf-8");
            //获取下载文件的目录
            ServletContext context = request.getSession().getServletContext();
            System.out.println("下载文件目录:" + context);
            String fileSavePath = context.getRealPath("/WEB-INF/upload/");
            System.out.println(fileSavePath + "\\" + fileName);
            //获取需要下载的文件
            File file = new File(fileSavePath + "\\" + fileName);
            //若文件不存在
            if (!file.exists()) {
                message = "您要下的资源不存在!";
                request.setAttribute("message", message);
                System.out.println("您要下的资源不存在!");
                return;
            }
            //处理文件名
            String realName = fileName.substring(fileName.indexOf("_") + 1);
            //设置响应头,控制浏览器下载该文件
            response.setHeader("content-disposition", "attachment;filename="
                    + URLEncoder.encode(realName, "UTF-8"));
            //读取要下载的文件,保存到文件输入流
            FileInputStream fis = new FileInputStream(fileSavePath + "\\" + fileName);
            OutputStream os = response.getOutputStream();
            //创建缓冲区
            byte buffer[] = new byte[1024*1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            fis.close();
            message = "下载成功!";
            message += "下载内容:" + realName + "<br>";
        } catch (Exception e) {
            message = "文件下载失败,请重新下载!";
            throw new Exception(e);
        }
        request.setAttribute("message", message);
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

}

4.测试
这里写图片描述
这里写图片描述
这里写图片描述
可以看到文件下载成功

四、上传与下载的完善

上传与下载是很简单的网络请求,本文实现的是很基础的上传与下载,还可以更好的完善。比如:增加数据库板块,文件获取从数据库中而来;下载列表进行分页;对下载请求来源进行辨别,防止盗链等等。

猜你喜欢

转载自blog.csdn.net/weixin_42880312/article/details/82080114