本文为大家分享了java实现文件上传下载功能的具体代码,供大家参考,具体内容如下
前端通过form表单的enctype属性,将数据传递方式修改为二进制”流“的形式,服务端(servlet)通过 getinputstream() 获取流信息, 运用java i/o 流的基础操作将流写入到一个服务端临时创建的文件temp中,然后再次利用文件基本操作,读取并截取临时文件内容,根据其中信息创建相应的文件,将读取出来的具体信息写入,下载时,根据提交的文件名称,找到服务器端相应的文件,然后根据输出流outstream输出到页面,同时将servlet的响应类型和响应头进行设置。
具体传输流程如下图:
流信息的部分为:
具体代码如下:
前端代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<html>
<head>
<meta http-equiv= "content-type" content= "text/html; charset=utf-8" >
<title>insert title here</title>
<script src= "js/jquery.js" ></script>
</head>
<body>
<form action= "fileupservlet" method= "post" enctype= "multipart/form-data" >
<table>
<tr>
<td>请选择上传文件:</td><td><input id= "myfile" name= "myfile" type= "file" value= "" /></td>
<td><input type= "submit" value= "上传" ></td>
</tr>
<tr><td>${info}</td></tr>
</table>
</form>
文件下载:<a href= "fileloadownservlet?filename=${filename}" >${filename}</a>
</body>
</html>
|
上传servlet部分(核心)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
@webservlet ( "/fileupservlet" )
public class fileupservlet extends httpservlet {
private static final long serialversionuid = 1l;
/**
* @see httpservlet#httpservlet()
*/
public fileupservlet() {
super ();
// todo auto-generated constructor stub
}
/**
* @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
*/
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
// todo auto-generated method stub
dopost(request, response);
}
/**
* @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
*/
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
// todo auto-generated method stub
request.setcharacterencoding( "utf-8" );
inputstream filesource = request.getinputstream(); //request获取流信息
string tempname = "d:/temp" ; //tempfile代表临时存放文件
file tempfile = new file(tempname); //创建临时文件
fileoutputstream outputstream = new fileoutputstream(tempfile); //输出流对象,指定输出指tempfile目录下
byte b[] = new byte [ 1024 ];
int n;
while ((n = filesource.read(b))!= - 1 ) //从输出流中每次读取1024字节,直至读完
{
outputstream.write(b, 0 ,n);
}
outputstream.close();
filesource.close(); //关闭输入输出流
/*以下为具体的文件操作,主要为解析临时产生的 temp文件 ,知识多为java输入输出流的内容!*/
randomaccessfile randomfile = new randomaccessfile(tempfile, "r" ); //随机流,指定要读临时文件,只读
randomfile.readline(); //读取第一行,无效数据,不需要
string str = randomfile.readline(); //读取第二行
int beginindex = str.lastindexof( "=" )+ 2 ; //指定所需数据的开始位置
int endindex = str.lastindexof( "\"" ); //指定所需数据截至位置
string filename = str.substring(beginindex,endindex); //截取文件名
//重新定位文件指针,获取文件内容
randomfile.seek( 0 ); //文件指针从头开始
long startext = 0 ;
int i = 1 ;
//文件内容开始位置
while ((n=randomfile.readbyte()) != - 1 &&i <= 4 )
{
if (n== '\n' )
{
startext = randomfile.getfilepointer();
i++;
}
}
startext = randomfile.getfilepointer() - 1 ;
//获取文件内容 结束位置
randomfile.seek(randomfile.length());
long endtext = randomfile.getfilepointer();
int j = 1 ;
while (endtext >= 0 && j <= 2 )
{
endtext--;
randomfile.seek(endtext);
if (randomfile.readbyte()== '\n' )
{
j++;
}
}
endtext = endtext- 1 ;
//将临时文件保存至指定目录中
string realpath = getservletcontext().getrealpath( "/" )+ "images" ; //设置文件保存目录
system.out.println(realpath);
file fileupload = new file(realpath);
if (!fileupload.exists())
{
fileupload.mkdir(); //目录不存在则创建
}
file savefile = new file(realpath,filename);
randomaccessfile randomaccessfile = new randomaccessfile(savefile, "rw" );
randomfile.seek(startext);
while (startext<endtext){
randomaccessfile.write(randomfile.readbyte()); //文件写入
startext = randomfile.getfilepointer();
}
//关闭各种输入输出流
randomaccessfile.close();
randomfile.close();
tempfile.delete(); //删除临时文件
simpledateformat timed = new simpledateformat( "yyyy-mm-dd hh:mm:ss" );
date nowdate = new date();
string time = timed.format(nowdate.gettime());
request.setattribute( "info" , time+ " " +filename+ "上传成功!" );
request.setattribute( "filename" , filename);
request.getrequestdispatcher( "/fildeop.jsp" ).forward(request, response);
}
}
|
下载部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
// todo auto-generated method stub
string filename = request.getparameter( "filename" );
string path = getservletcontext().getrealpath( "/" )+ "images/" ;
file file = new file(path+filename); //找到文件
if (file.exists())
{
response.setcontenttype( "application/x-msdownload" ); //设置响应类型,此处为下载类型
response.setheader( "content-disposition" , "attachment;filename=\"" +filename+ "\"" ); //以附件的形式打开
inputstream inputstream = new fileinputstream(file);
servletoutputstream outputstream = response.getoutputstream();
byte b[] = new byte [ 1024 ];
int n;
while ((n = inputstream.read(b)) != - 1 )
{
outputstream.write(b, 0 ,n);
}
outputstream.close();
inputstream.close();
} else {
request.setattribute( "result" , "文件不存在!下载失败!" );
request.getrequestdispatcher( "/fildeop.jsp" ).forward(request, response);
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/TheGCC/archive/2018/04/26/8951774.html