5fc928230abfe2739.jpg_fo742.jpg

CommonReturnType.java

public class CommonReturnType {
    private String status;
    private Object data;

    public static CommonReturnType create(Object result){
        return CommonReturnType.create(result,"sueccess");
    }

    public static CommonReturnType create(Object result, String status){
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setStatus(status);
        commonReturnType.setData(result);
        return commonReturnType;
    }
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}


download.java

    @GetMapping("/download/{fileName}")
    public CommonReturnType downloadFile(@PathVariable("fileName") String name, HttpServletResponse response) throws UnsupportedEncodingException {

        String filePath="D:/Desktop/mow/upload";  //文件的根目录
        File file=new File(filePath+"/"+name); //处理用的文件类,用于操作这个目录下的文件
        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(name,"UTF-8"));  //为了下载的东西不乱码而设置前三个格式

            byte[] buffer=new byte[1024]; //每次读取的最大字节数
            FileInputStream fis=null;  //建立缓冲输入字节流
            BufferedInputStream bis=null;
            OutputStream os=null;
            try {
                os=response.getOutputStream();//向response缓冲区中写入字节
                fis=new FileInputStream(file);
                bis=new BufferedInputStream(fis);
                int i=bis.read(buffer);  //读取缓存,若读不到返回-1
                while(i!=-1){
                    os.write(buffer);
                    i=bis.read(buffer);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("----------file download---" + name);
            try{
                bis.close();  //关闭流
                fis.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            return null;
        }
        return null;
    }

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code