_xkoko
COCO 很懒 什么都没留下......
package com.XXXX.utils;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.nskj.supcheck.entity.SupPlanAdjunct;

public class DownloadFile {

    public static ResponseEntity<byte[]> downloadFile(HttpServletRequest request,String filePath,String fileName)throws Exception{
    //public ResponseEntity<byte[]> DownloadFile(HttpServletRequest request,HttpServletResponse response,String filePath,String fileName)throws Exception{
         //  接受的是UTF-8
        request.setCharacterEncoding("utf-8");
           //获取项目根目录(下载目录)
        String path = request.getSession().getServletContext().getRealPath(filePath);  

        String userAgent = request.getHeader("User-Agent");
           File file = null;
           HttpHeaders headers =null;
           String fileName1 =null;
           try {
            //  System.out.println(filename);//myfiles
              file =new File(path);
            //  System.out.println(file);
              //请求头
              headers =new HttpHeaders();
              //进行浏览器乱码处理
              if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {  
                  fileName1 = java.net.URLEncoder.encode(fileName, "UTF-8");  
                } else {  
                    // 非IE浏览器的处理:  
                    fileName1 = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");  
                }  
              //通知浏览器以attachment(下载方式)打开
              headers.setContentDispositionFormData("attachment",fileName1);
              //application/octet-stream二进制流数据(最常见的文件下载)。
              headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
              headers.set("Content-Disposition","attachment;filename="+fileName1);

           } catch (Exception e) {
              throw new RuntimeException(e);
           }
           return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }
}

 

posted on 2018-08-08 14:45  _xkoko  阅读(105)  评论(0)    收藏  举报