public ResponseMsg<String> downLoadResource(HttpServletRequest request, HttpServletResponse response) throws IOException {
URL url = null;
DataInputStream in=null;
ServletOutputStream out=null;
try{
String resourceId = (String)request.getParameter("resourceId");
//根据资源id查询资源相关信息
cn.ulearning.jxpt.resource.domain.Resource resourceInfo = resourceService.getResource(resourceId);
if(resourceInfo !=null) {
//文件名字
String fileName = resourceInfo.getName();
//文件路径
String Path = resourceService.getResourceDoloadUrlById(resourceInfo.getResourceCenterId());
JSONObject filePathJsonObject = JSONObject.parseObject(Path);
if(filePathJsonObject !=null && filePathJsonObject.containsKey("downloadUrl")) {
String filePath = ((String)filePathJsonObject.get("downloadUrl"));
if(null !=filePath && !"".equals(filePath)){
// 设置response
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form--/;charset="+ "UTF-8");
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes(System.setProperty("sun.jnu.encoding","utf-8")), "ISO8859-1" ) );
// 生成文件输入字节流
url = new URL(filePath);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
response.setHeader("Content-Length", ""+urlCon.getContentLength());
in = new DataInputStream(urlCon.getInputStream());
// 生成文件输出字节流
out = response.getOutputStream();
// 字节数组
byte[] tmp = new byte[1024];
// 读取字节长度
int length = 0;
while ((length = in.read(tmp)) > 0)
{
out.write(tmp, 0, length);
}
out.flush();
}else{
return new ResponseMsg<String>(ResponseCode.FAIL,"资源不存在!");
}
}
}else{
return new ResponseMsg<String>(ResponseCode.FAIL,"资源不存在!");
}
}catch(Exception e) {
logger.error("/downLoadResource-ErrorMsg:",e);
return null;
}finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
return null;
}
Content-Disposition属性有两种类型:inline 和 attachment inline :将文件内容直接显示在页面 attachment:弹出对话框让用户下载