前端代码
function downloadFile() {
var url = 'http://192.168.1.123:8080/MT/metadataManagement/exportMetadataToExcel?metadataid=2070&filename=测试';
window.location.href = url;
}
- 前端不使用ajax,因为ajax会把数据放进浏览器内存无法实现下载
- 不使用post请求,直接将参数加入url中
后台代码
@RequestMapping(value = "/exportMetadataToExcel",method = RequestMethod.GET)
@ResponseBody
@Log(operationType="metadata",operationDesc="导出元数据到excel")
public JSONObject exportMetadataToExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
JSONObject responsejson = new JSONObject();
GlobalMethodAndParams.setHttpServletResponse(request, response);
String metadataid = request.getParameter("metadataid");
String filename =request.getParameter("filename");
HSSFWorkbook wb = metadataManagementService.exportMetadataToExcel(metadataid);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+ new String((filename + ".xls").getBytes("utf-8"), "utf-8"));
ByteArrayOutputStream os = new ByteArrayOutputStream();
wb.write(os);
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
ServletOutputStream out = response.getOutputStream();
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
responsejson.put("result", true);
responsejson.put("count",1);
}catch (IOException e) {
responsejson.put("result", false);
responsejson.put("count",0);
}finally{
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return responsejson;
}