jsp如何实现文件下载,d出提示框那种

jsp如何实现文件下载,d出提示框那种,第1张

可以采用:

1、RequestDispatcher的方式进行;

2、采用文件流输出的方式下载

1、采用RequestDispatcher的方式进行

jsp页面中添加如下代码:

<%

response.setContentType("application/x-download")//设置为下载application/x-download

String filedownload = "/要下载的文件名"//即将下载的文件的相对路径

String filedisplay = "最终要显示给用户的保存文件名"//下载文件时显示的文件保存名称

filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8")

response.addHeader("Content-Disposition","attachmentfilename=" + filedisplay)

try

{

RequestDispatcher dis = application.getRequestDispatcher(filedownload)

if(dis!= null)

{

dis.forward(request,response)

}

response.flushBuffer()

}

catch(Exception e)

{

e.printStackTrace()

}

finally

{

}

%>

2、采用文件流输出的方式下载

<%@page language="java" contentType="application/x-msdownload"pageEncoding="gb2312"%><%

//关于文件下载时采用文件流输出的方式处理:

//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;

response.reset()//可以加也可以不加

response.setContentType("application/x-download")

String filedownload = "想办法找到要提供下载的文件的物理路径+文件名"

String filedisplay = "给用户提供的下载文件名"

filedisplay = URLEncoder.encode(filedisplay,"UTF-8")

response.addHeader("Content-Disposition","attachmentfilename=" + filedisplay)

OutputStream outp = null

FileInputStream in = null

try

{

outp = response.getOutputStream()

in = new FileInputStream(filenamedownload)

byte[] b = new byte[1024]

int i = 0

while((i = in.read(b)) >0)

{

outp.write(b, 0, i)

}

outp.flush()

}

catch(Exception e)

{

System.out.println("Error!")

e.printStackTrace()

}

finally

{

if(in != null)

{

in.close()

in = null

}

if(outp != null)

{

outp.close()

outp = null

}

}

%>

在wsad里面写JSP文件下载,总是出现这个异常,getOutputStream() has already been called for this response,输出流已经被调用了.

上网查半天终于明白一点,JSP早下载文件的时候用到了OutputStream,而在Application Server在处理编译jsp时对于%>和<%之间的内容一般是原样输出,而且默认是PrintWriter.

//给input添加如下事件 一开始默认设置内容为 请输入姓名  获得焦点输入内容后 清空

$(function(){

var n = $('#name')

n.val('请输入姓名')

n.focus(function(){

$(this).val('')

}).blur(function(){

$(this).val('请输入姓名')

})

})

focus是获取焦点事件 即用户输入时清除提示信息

或者给input标签加上 placeholder属性  该设置可以使得没有输入时显示默认内容 输入之后清除默认提示内容

<input name="username"  placeholder="请输入姓名"/>

jsp页面可以利用href调用javascript方法进行延时来实现点击连接后延迟跳转。

比如在页面上可以这么写:

<a href="javascript:xxx()">下一页</a>

//设置延时函数

function sleep(numberMillis) {

var now = new Date()

var exitTime = now.getTime() + numberMillis

while (true) {

now = new Date()

if (now.getTime() >exitTime)

return

}

然后调用sleep(1000)xxx()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11821782.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存