群里面中山的陈先生问,我想在BS展现出文件,然后让用户下载文件,我现在的文件是存放在数据库中,如何下载下来呢?
那我今天来讲讲文件下载的两个方法
文件名:1.pdf,存放于框架中的wwwroot目录下的image目录
1 直接下载
直接用 http://127.0.0.1:801/image/1.pdf即可下载文件
2 流式下载
流式下载是文件存在内存变量中,直接往前端输出。
代码如下:
类名:A4file,过程名GetPDF
myfile=Filetostr(getwwwrootpath()+"1.pdf")
cContype=getContentByExtName("pdf")&&根据扩展名得到 content-type
setContentType(cContype) &&设置发送头
Return myfile问题来了,直接发送文件流是没有文件名的,也就是前端是没有办法知道文件名是什么?
那我们用xml包起来如何呢?
myfile=Filetostr(getwwwrootpath()+"1.pdf")
TEXT TO lcReturn noshow TEXTMERGE
<file>1.pdf</file>
<filedata><<myfile>></filedata>
ENDTEXT
Return lcReturn 到时取得的XML再解析拆出来就好。
也可以把文件名放在Http请求头中
myfile=Filetostr(getwwwrootpath()+"1.pdf")
cContype=getContentByExtName("pdf")&&根据扩展名得到 content-type
setResponseHeader("file","1.pdf")&&设置HTTP请求头
setContentType(cContype) &&设置发送头
Return myfile
上文的myfile 也可以从数据库取得,你学会了吗?前端JQ代码这样写
$(document).ready(function(){
$.ajax({
url: "a4file.fsp?proc=getpdf",
type: "GET",
data: "",
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
alert(textStatus + " : " +errorThrown);
} else {
alert(textStatus);
}
},
success: function(data, textStatus, jqXHR) {
alert(jqXHR.getResponseHeader("file"));
}
});
});