DataTable中的一列添加实现文件下载
{"data": "filename","sDefaultContent" : "","sClass" : "hidden-480",
render: function(data,type,row,meta){
if (row.drawingtype=='05'){
return '<a href="javascript:download(''+row.drawingkey+'')">'+data+'</a>';
}
else
return data;
}
},
解释一下
href="javascript:download(''+row.drawingkey+'')">'+data+'</a>'
和
<a href="javascript:void(0);" οnclick="download(key)">fdsffsdf</a>
效果类似,两种写法都可以,
然后编写download方法就行了
function download(drawingkey){
//location.href="${ctx}/pims/draw/download?key="+drawingkey;
var url='${ctx}/pims/draw/download';
var params={"key": drawingkey};
$.ajax({
//提交数据的类型 POST GET
type:"POST",
//提交的网址
url:url,
data:params,
//返回数据的格式
datatype: "blob",
//成功返回之后调用的函数
success: function(response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) { //判断是否为文件
var form = $('<form method="POST" action="' + url + '">');
$.each(params, function(k, v) {
debugger;
form.append($('<input type="hidden" name="' + k +'" value="' + v + '">'));
});
$('body').append(form);
form.submit(); //自动提交
}
},
//调用出错执行的函数
error: function(response, status, request){
if(status == 'error'){
layer.alert('文件不存在', {
skin: 'layui-layer-lan',
icon: 5,
closeBtn: 0,
anim: 3 //动画类型
});
}
});
}
前台就写完了,后台注意一下用你自己的路径,我的路径都是从数据库中查出来的,把自己的路径替换上去就好了
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(HttpServletRequest request, String key) throws Exception {
Pimsawing pimsawing = pimsawingService.findById(key);
String realPath = pimsawing.getFilepath();
//String fileName = pimsDrawing.getFilename();
String sourceName = pimsawing.getSourcename();
File file = new File(realPath + sourceName);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", sourceName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
//或者
Pimsawing pimsawing = pimsawingService.findById(key);
HttpHeaders headers = new HttpHeaders();
InputStream fis = null;
byte[] buffer = null;
try {
String realPath = pimsDrawing.getFilepath();
String sourceName = pimsDrawing.getSourcename();
File file = new File(realPath+sourceName);
//String filename = file.getName();
headers.setContentDispositionFormData("attachment", sourceName);
fis = new BufferedInputStream(new FileInputStream(file));
buffer= new byte[fis.available()];
fis.read(buffer);
return new ResponseEntity<byte[]>(buffer,headers,HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<byte[]>(buffer,headers,HttpStatus.NOT_FOUND);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样就实现了文件的下载功能了,也可以使用get方法做,后台不变,前台使用<a标签来实现跳转的功能