zoukankan      html  css  js  c++  java
  • 文件下载

    package com.neuedu.controller;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    @Controller
    public class Down {
        
        @RequestMapping("/testResponseEntity")
        public ResponseEntity<byte[]> testResponseEntity(HttpServletRequest request) throws Exception{
    //        得到整个web应用的对象
            ServletContext servletContext = request.getServletContext();
    //        文件名
            String  fileName="风吹麦浪.mp3";
    //        得到文件的真实路径
            String realPath = servletContext.getRealPath("/WEB-INF/"+fileName);
    //        得到输入对象对象流
            InputStream in=new FileInputStream(new File(realPath));
    //        创建一个数组,准备接收文件流
            byte[]body=new byte[in.available()];
    //        将文件输入数组
            try {
                in.read(body);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            
            MultiValueMap<String, String>headers=new HttpHeaders();
    //        w文件名的编码问题
            try {
                fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    //        保证下载的时候不会播放文件
            headers.set("Content-Disposition", "attachment; filename="+fileName);
            
             HttpStatus statusCode=HttpStatus.OK;
            ResponseEntity<byte[]>response=new ResponseEntity<byte[]>(body, headers, statusCode);
            return response;
            
            
            
        }
    
    }
  • 相关阅读:
    _getch()函数的一些使用方法
    键盘敲击(keyboard hit)
    计时 GetTickCount() 函数的作用和用法
    1
    关于COLORREF的定义及用法
    C++字符串大小写转换的库函数
    数楼梯(斐波那契数列+高精度)
    回文数(内含高精度加法,字符串是否为回文的判断)
    最短路径Dijkstra算法
    经典八大排序
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7425305.html
Copyright © 2011-2022 走看看