SpringMVC实现文件下载

前段时间作项目用Plupload实现了文件分块上传SSM框架+Plupload实现分块上传(Spring+SpringMVC+MyBatis+Plupload),项目仅有文件上传还不够,还应提供文件下载。接下来就在原来项目基础上(SSM框架,Spring+SpringMVC+MyBatis)实现文件下载。并在最后给出效果图。html


一:前端请求下载:前端

关于下载这部分的前端效果是用jq append的,没在jsp里写htmljava

$("#shareFileDiv"+fileItems[i]["id"]).append('<a href="'+basePath+'/youandme/downloadFile/'+fileItems[i]["id"]+'" class="shareFileDownload">'+"下载"+'</a>'

你只须要关注append函数里的a标签,这个a标签就是每一个文件对应的下载按钮。其中basePath的定义为:String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; path的定义为:String path = request.getContextPath(); 这里稍做请求路径解释:先拿到服务器名,再是端口号(服务器+端口号下就是你发布到Tomcat的不少javaweb项目),再是上下文路径(该项目文件夹下),这样basePath路径下就是你们熟悉的META-INF,WEB-INF,index.jsp。以Servlet容器的角度看,这个basePath下实际上是一个SpringIOC容器,里面有我写好的各个bean,Service与Controller对象(SpringMVC用于映射),相信熟悉Spring与SpringMVC的大家都知道这些。web


二:Controller映射请求spring

@Controller
@RequestMapping(value = "/youandme")
public class youandmeController {

    @Autowired
    private MyDownload myDownload;

    @RequestMapping(value = "/downloadFile/{id}")
    public void downloadFile(@PathVariable("id") int id,HttpServletRequest request,HttpServletResponse response){
        try {
            int userId = ((User)(request.getSession().getAttribute("user"))).getUserId();
            myDownload.downloadSolve(id,request,response,userId);
        }catch (ServletException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

@PathVariable(“id”) int id获得请求URL中的参数id,是该文件相应信息在数据库的惟一标识。数据库


三:MyDownload类(Service)浏览器

package web.download;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import service.youandmeService;

@Component
public class MyDownload{

    @Autowired
    private youandmeService youandmeService;

    public void downloadSolve(int id,HttpServletRequest request, HttpServletResponse response,int userId) throws ServletException, IOException {

        //根据文件id在数据库中获取文件名
        String fileName = (youandmeService.showFileOfId(id)).getFileName();
        //文件所在目录路径
        String filePath = request.getSession().getServletContext().getRealPath("/")+"pluploadDir/"+userId+"/";
        //获得该文件
        File file = new File(filePath+fileName);
        if(!file.exists()){
            System.out.println("Have no such file!");
            return;//文件不存在就退出方法
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        //设置Http响应头告诉浏览器下载这个附件
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }
}
  1. 重要的注释都在代码中给出了。类头上的@Component注解是为了告诉SpringMVC,将这个写好的类注入到SpringIOC容器中以待使用(Controller就经过@Autowired注解自动装载了这个类并使用)。类中经过@Autowired装载了我用MyBatis与Spring封装的youandmeService对象,这个对象负责整个项目的数据库操做。
  2. 再提一遍response.setHeader,这个是设置响应头信息,attachment中文是附件的意思,告诉浏览器去下载它;URLEncoder.encode解决文件名中文乱码问题。

写到这里,关于下载模块的代码已经所有给出了,下面就给出效果图:服务器

服务器中有以下文件供下载:markdown

这里写图片描述

这里写图片描述

选中文件开始下载:app

这里写图片描述

这里写图片描述

下载完成后电脑本地有相应文件:

这里写图片描述


若有问题或补充,请你们在评论中尽管提,共同交流^~^。