controller
@RequestMapping("downloadFile")
public void downloadData(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
DataRadarFarStation dataRadarFarStation = dataRadarFarStationService.selectDataRadarFarStationById(id);
//要下载的文件名 从前台传来
String fileNameNeedDown = dataRadarFarStation.getFileName();
//这里的路径是要下载的文件所在路径
String realPath = dataRadarFarStation.getFilePath();
File file = null;
file = new File(realPath);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
String aFileName = null;
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0)
|| ((agent.indexOf("RV") != -1) && (agent
.indexOf("FIREFOX") == -1))) {
aFileName = URLEncoder.encode(fileNameNeedDown, "UTF-8");
} else {
aFileName = new String(fileNameNeedDown.getBytes("UTF-8"), "ISO8859-1");
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ aFileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
bis = new BufferedInputStream(new FileInputStream(new File(realPath)));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
System.out.println("success");
bos.flush();
} catch (Exception e) {
System.out.println("失败!");
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (Exception e) {
}
}
}
service
public DataRadarFarStation selectDataRadarFarStationById(String id)
impl
@Override
public DataRadarFarStation selectDataRadarFarStationById(Long dataId)
{
return DataRadarFarStation .selectDataRadarFarStationById(dataId);
}
mapper
public DataGts2Query selectDataRadarFarStationById(Long dataId);
sql