Spring MVC 文件下载

Spring MVC 文件下载

首先在springmvc.xml配置上传

<bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1024000"/>
    </bean>

然后写下载文件的Controller

@Controller
@RequestMapping("download")
public class DownloadController {
    /**
     * 下载文件
     * @param fileName
     * @param requset
     * @param response
     */
    @RequestMapping("download")
    public String download(String fileName,HttpServletRequest requset,HttpServletResponse response){
        //fileName是需要下载的文件名字
        response.setContentType("text/html;charset=utf-8");
        try {
            requset.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //输出输出流
        BufferedInputStream bis=null;
        BufferedOutputStream bio=null;

        //获取文件路径
        String ctxPath = requset.getSession().getServletContext().getRealPath("/")+"upload/";
        //文件真是存放地址
        String downloadPath=ctxPath+fileName;
        System.out.println(downloadPath);
        try {
            //获取文件长度
            long fileLength = new File(downloadPath).length();
            //设置返回头
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Length", fileLength+"");
            response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes(),"iso8859-1"));
            //获取输入输出流
            bis = new BufferedInputStream(new FileInputStream(downloadPath));
            bio = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048]; 
            int bytesRead;
            while((bytesRead = bis.read(buff, 0, buff.length)) != -1){
                bio.write(buff, 0 , bytesRead );
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            //关闭输入流
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //关闭输出流
            if(bio!=null){
                try {
                    bio.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值