zoukankan      html  css  js  c++  java
  • 浏览器下载服务端文件

    package com.excel.controller;

    import com.alibaba.excel.ExcelWriter;import org.springframework.web.bind.annotation.GetMapping;
    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 java.io.File;
    import java.io.FileInputStream;
    import java.io.OutputStream;

    /**
    * 下载文件
    * @author : tony
    * @version :1.0
    */
    @RequestMapping("/excel")
    @RestController
    public class ExcelController {

    /**
    * 下载已经生成好的文件
    * @param request
    * @param response
    */
    @GetMapping("/downExcel.action")
    public void download1Excel(HttpServletRequest request, HttpServletResponse response){
    OutputStream out = null;
    ExcelWriter excelWriter = null;
    File file = null;
    FileInputStream input = null;
    try {
    out = response.getOutputStream();
    //设置ConetentType CharacterEncoding Header,需要在out.write()之前设置
    // 设置头信息
    response.setCharacterEncoding("UTF-8");
    // 告诉浏览器用什么软件可以打开此文件
    response.setHeader("content-Type", "application/vnd.ms-excel");

    // 下载文件的默认名称
    response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));


    //本地已存在的文件
    file = new File("excelByModel.xlsx");
    input = new FileInputStream(file);
    int len;
    byte[] bytes = new byte[1024];
    while((len =input.read(bytes))> 0){
    out.write(bytes,0,len);
    }
    out.flush();
    }catch (Exception e){
    e.printStackTrace();
    }finally {
    try {
    input.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    out.close();
    }catch (Exception e){
    e.printStackTrace();
    }
    }
    }
    }

    ******未经允许,禁止转载 否则追究法律责任******
  • 相关阅读:
    Python Xcode搭建Python环境以及使用PyCharm CE
    Python 集体智慧编程PDF
    Swift tableview自带的刷新控件
    iOS 类似朋友圈的图片浏览器SDPhotoBrowser
    程序员应掌握的算法
    C++ 知识点总结复习
    iOS 图片的拉伸,取固定区域显示
    iOS 获取一个不变的UDID
    iOS 应用中加载文档pdf/word/txt
    LeetCode-Design Snake Game
  • 原文地址:https://www.cnblogs.com/demo-tt/p/14072242.html
Copyright © 2011-2022 走看看