import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import com.talkweb.dao.FILE_RECORDMapper; import com.talkweb.po.FILE_RECORD; @Controller public class DownloadFileController { private static Logger logger = Logger.getLogger(DownloadFileController.class); @Autowired FILE_RECORDMapper fILE_RECORDMapper; @RequestMapping(value = "/downloadFile") public ResponseEntity<byte[]> downloadFile(Long D_file_id,HttpServletRequest request) { try { logger.info("文件下载接口被调用,接收到参数:[D_file_id:" + D_file_id + "]"); FILE_RECORD fILE_RECORD = fILE_RECORDMapper.selectByPrimaryKey(D_file_id); String sFilePath = fILE_RECORD.getsFilePath(); String sFileName = fILE_RECORD.getsFileName(); String rFileName = fILE_RECORD.getrFileName(); String fullFilePath = sFilePath+sFileName; InputStream in=new FileInputStream(new File(fullFilePath));//将该文件加入到输入流之中 byte[] body=null; body=new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数 in.read(body);//读入到输入流里面 rFileName=new String(rFileName.getBytes("gbk"),"iso8859-1");//防止中文乱码 HttpHeaders headers=new HttpHeaders();//设置响应头 headers.add("Content-Disposition", "attachment;filename="+rFileName); HttpStatus statusCode = HttpStatus.OK;//设置响应吗 ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode); return response; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("文件下载异常:"+e.toString()); } logger.error("文件下载异常,未知原因"); return null; } }