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