• 文件下载


    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;
            
            
            
        }
    
    }
  • 相关阅读:
    C#调用Exe文件的方法及如何判断程序调用的exe已结束(转)
    C# Color (转)
    【666】语义分割减少过拟合
    【665】构建多损失函数
    libc timer
    分支管理
    MULLS:论文阅读
    微信支付宝整合支付开发中的常见问题
    IIS8中安装和使用URL重写工具(URL Rewrite)的方法
    通过Java 技术手段,检查你自己是不是被绿了...
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7425305.html
Copyright © 2020-2023  润新知