码迷,mamicode.com
首页 > 其他好文 > 详细

文件下载

时间:2017-08-24 22:33:43      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:com   iso   package   logs   control   gets   support   get   code   

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;
        
        
        
    }

}

 

文件下载

标签:com   iso   package   logs   control   gets   support   get   code   

原文地址:http://www.cnblogs.com/xuesheng/p/7425305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!