SpringMVC实现文件下载

转自:http://blog.csdn.net/qq_33290787/article/details/52334826

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


一:前端请求下载:

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

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

你只需要关注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的你们都知道这些。


二:Controller映射请求

@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解决文件名中文乱码问题。

写到这里,关于下载模块的代码已经全部给出了,下面就给出效果图:

服务器中有如下文件供下载:

这里写图片描述

这里写图片描述

选中文件开始下载:

这里写图片描述

这里写图片描述

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

这里写图片描述


如有问题或补充,请大家在评论中尽管提,共同交流^~^。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值