上传:
MyjspForm mf = (MyjspForm) form// TODO Auto-generated method stub
FormFile fname=mf.getFname()
byte [] fn = fname.getFileData()
OutputStream out = new FileOutputStream("D:\\"+fname.getFileName())
Date date = new Date()
String title = fname.getFileName()
String url = "d:\\"+fname.getFileName()
Upload ul = new Upload()
ul.setDate(date)
ul.setTitle(title)
ul.setUrl(url)
UploadDAO uld = new UploadDAO()
uld.save(ul)
out.write(fn)
out.close()
下载:
DownloadForm downloadForm = (DownloadForm)form
String fname = request.getParameter("furl")
FileInputStream fi = new FileInputStream(fname)
byte[] bt = new byte[fi.available()]
fi.read(bt)
//设置文件是下载还是打开以及打开的方式msdownload表示下载;设置字湖集,//主要是解决文件中的中文信息
response.setContentType("application/msdownloadcharset=gbk")
//文件下载后的默认保存名及打开方式
String contentDisposition = "attachmentfilename=" + "java.txt"
response.setHeader("Content-Disposition",contentDisposition)
//设置下载长度
response.setContentLength(bt.length)
ServletOutputStream sos = response.getOutputStream()
sos.write(bt)
return null
<%@pagelanguage="java" import="java.io.*,java.net.*" contentType="application/x-msdownload"pageEncoding="UTF-8"%><%//关于文件下载时采用文件流输出的方式处理:
//加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
String url = request.getParameter("url")
System.out.print(url)
int k = url.lastIndexOf("\\")
String url1=url.substring(k+1,url.length())
response.reset()//可以加也可以不加
response.setContentType("application/x-download")
String filedownload = url
String filedisplay = url1
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(filedownload)
byte[] b = new byte[1024]
int i = 0
while((i = in.read(b)) >0)
{
outp.write(b, 0, i)
}
out.clear()
out = pageContext.pushBody()
outp.flush()
}
catch(Exception e)
{
System.out.println("Error!")
}
finally
{
if(in != null)
{
in.close()
in = null
}
if(outp != null)
{
outp.close()
outp = null
}
}
%>
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文件,根据需求修改即可。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)