文件下载

package com.example.demo.Controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.*;


@RestController
public class FileDownloadController {
    @RequestMapping("download")
    public ResponseEntity download(HttpServletRequest request, HttpServletResponse response,String filename)throws Exception{
        String path = request.getServletContext().getRealPath("upload");
        System.out.println(path);
        File file = new File(path + File.separator + filename);
        System.out.println(file);
        if(file.exists()){
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition","attachment:filename="+ java.net.URLEncoder.encode(filename,"utf-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;   //输入流
            OutputStream   os=null;   //输出流
            BufferedInputStream bis = null; //缓冲流
            try {
                os=response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                bis.close();
                fis.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }
}

你可能感兴趣的:(文件下载)