jsp开发之文件下载

步骤如下:

1、写一个jsp页面。(就写一个连接就行了)

jsp开发之文件下载_第1张图片

jsp开发之文件下载_第2张图片

2,配置web.xml(前端我利用的是springMVC)

jsp开发之文件下载_第3张图片

3、导入jar包(我利用的是maven注入)




  4.0.0

  com.nfha.wyz
  wyz
  1.0-SNAPSHOT
  war

  wyz Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
  

  
    
      junit
      junit
      4.11
      test
    
    
    
      commons-io
      commons-io
      2.6
    
    
    
      org.springframework
      spring-core
      4.1.7.RELEASE
    
    
      org.springframework
      spring-beans
      4.1.7.RELEASE
    
    
      org.springframework
      spring-tx
      4.1.7.RELEASE
    
    
      org.springframework
      spring-context
      4.1.7.RELEASE
    
    
      org.springframework
      spring-context-support
      4.1.7.RELEASE
    

    
      org.springframework
      spring-web
      4.1.7.RELEASE
    

    
      org.springframework
      spring-webmvc
      4.1.7.RELEASE
    
  

  
    wyz
    
      
        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

4,写aplicationContext.xml



    
    
    
    
    
    

 

5,编写controller

package com.*.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@Controller
public class DemoController {
    @RequestMapping("download")
    public void downlode(String fileName, HttpServletResponse res, HttpServletRequest req)throws IOException {
        System.out.print("进入后台");
        //设置响应流中文件进行下载
        res.setHeader("Content-Disposition", "attachment;filename="+fileName);
        //把二进制流放入到响应体中.
        ServletOutputStream out=res.getOutputStream();
        String path = req.getServletContext().getRealPath("files");
        System.out.println(path);
        File file = new File(path, fileName);
        byte []bytes= FileUtils.readFileToByteArray(file);
        out.write(bytes);
        out.flush();
        out.close();

    }
}

OK了。就完成了。是不是很简单。下面是效果图。

jsp开发之文件下载_第4张图片

你可能感兴趣的:(jsp开发)