jsp页面如何实现下载文档

jsp页面如何实现下载文档,第1张

jsp页面下载文档是宴销在jsp中有一个a标签 ,当用户点击a标签的时候下载文件

一般采用链州href属性直接指向一个服务器地址,只要链接的文件存在,就会给出d出保存对话框.

点击a标签 先执行onclick事件,再请求href中指向的地址。

前端jsp:

<a href="#" onclick="javascript:downloadtest('${app.id}')" id="pluginurl" style="color: #83AFE2text-decoration:underline"></a>

然后在js中:

function downloadtest(id){

var url = "<%=request.getContextPath()%>/app/download" + "/" + id

$("#pluginurl").attr("href",url)

}

后台处理下载晌唤游逻辑的java代码:

/**

* 下载文件

* @param id appid

* @param response

*/

@RequestMapping(value="/download/{id}")

public void download(@PathVariable String id, HttpServletResponse response){

String filepath = ""

Result result = appService.getAppById(id)

App app = (App) result.getMap().get("app")

if(app == null){

return

}

filepath = app.getUrl()

File file = new File(filepath)

InputStream inputStream = null

OutputStream outputStream = null

byte[] b= new byte[1024]

int len = 0

try {

inputStream = new FileInputStream(file)

outputStream = response.getOutputStream()

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

String filename = file.getName()

filename = filename.substring(36, filename.length())

response.addHeader("Content-Disposition","attachmentfilename=" + URLEncoder.encode(filename, "UTF-8"))

response.setContentLength( (int) file.length( ) )

while((len = inputStream.read(b)) != -1){

outputStream.write(b, 0, len)

}

} catch (Exception e) {

e.printStackTrace()

}finally{

if(inputStream != null){

try {

inputStream.close()

inputStream = null

} catch (IOException e) {

e.printStackTrace()

}

}

if(outputStream != null){

try {

outputStream.close()

outputStream = null

} catch (IOException e) {

e.printStackTrace()

}

}

}

}

JSP页面点击超链接d出文件下载,核团代码如下:

<%

String path = request.getContextPath()

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"

%>

//然后

<a href ="<%= basePath %>/upload/aa.doc }" target="_blank"世扰>下&nbsp&nbsp载</a>

注:<%= basePath %>获取部署JSP项目的根目录,/upload/aa.doc/是根搜氏旦目录>upload>aa.doc文件,根据需求修改即可。

如果服务器端程序使用的是struts2框架的话,我会,其他的不会。纳碧

struts2:

对于上传,jsp页面只需要有个file类型的表单域,如<input type="file" name="xxx" />

struts2的接收请求的action中再写三个属性与这个表单域的名称对应起来世哗,他们是,File类型的xxx,String类型的xxxFileName,String类型的xxxContentType,并其设置相应的set/get方法。则框架负责接收上传搜茄行文件的字节流,解析文件名,文件类型,直接使用即可。

对于下载,只需要在action的配置文件中设置如下返回值类型和相应参数:

<result type="stream">

<param name="contentType">application/octet-stream</param>

<param name="inputName">inputStream</param>

<param name="contentDisposition">attachmentfilename=xxx </param>xxx为下载文件的文件名

</result>

且在action总写一个返回值类型为InputStream的getInputStream方法,此方法返回你要下载的文件的流即可。

ps:其中contentDisposition的配置信息中attachment代表点击下载时浏览器先d出个保存位置的提示框,然后再决定是否下载,默认是inline,即直接打开文件。


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

原文地址: https://outofmemory.cn/yw/12485659.html

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

发表评论

登录后才能评论

评论列表(0条)

保存