基于Java⽂件输⼊输出流实现⽂件上传下载功能
本⽂为⼤家分享了Java实现⽂件上传下载功能的具体代码,供⼤家参考,具体内容如下
前端通过form表单的enctype属性,将数据传递⽅式修改为⼆进制”流“的形式,服务端(servlet)通过 getInputStream() 获取流信息,运⽤java I/O 流的基础操作将流写⼊到⼀个服务端临时创建的⽂件temp中,然后再次利⽤⽂件基本操作,读取并截取临时⽂件内容,根据其中信息创建相应的⽂件,将读取出来的具体信息写⼊,下载时,根据提交的⽂件名称,到服务器端相应的⽂件,然后根据输出流outStream输出到页⾯,同时将servlet的响应类型和响应头进⾏设置。
具体传输流程如下图:
流信息的部分为:
window对象具体代码如下:
前端代码:
<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>
try catch和finally运行顺序<tr><td>${info}</td></tr>
</table>
</form>
⽂件下载:<a href="FileLoadownServlet?filename=${filename}">${filename}</a>
</body>
</html>
上传servlet部分(核⼼)
@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 = InputStream();//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 = ad(b))!= -1)//从输出流中每次读取1024字节,直⾄读完
{
outputStream.write(b,0,n);
}
outputStream.close();
filesource.close();//关闭输⼊输出流
/*以下为具体的⽂件操作,主要为解析临时产⽣的 temp⽂件,知识多为java输⼊输出流的内容!*/
RandomAccessFile randomfile = new RandomAccessFile(tempfile, "r");//随机流,指定要读临时⽂件,只读
String str = adLine();//读取第⼆⾏
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((adByte()) != -1&&i <= 4)
{
if(n=='\n')
{
startext = FilePointer();
i++;
}
}
startext = FilePointer() - 1;
/
/获取⽂件内容结束位置
randomfile.seek(randomfile.length());
long endtext = FilePointer();
int j = 1;
while(endtext >= 0 && j <= 2)
{
endtext--;
randomfile.seek(endtext);
adByte()=='\n')
{
j++;
}
}
endtext = endtext-1;
//将临时⽂件保存⾄指定⽬录中
String realpath = getServletContext().getRealPath("/")+"images";//设置⽂件保存⽬录
System.out.println(realpath);
File fileupload = new File(realpath);
if(!ists())
{
fileupload.mkdir();//⽬录不存在则创建
}
File savefile = new File(realpath,filename);
jquery下载文件请求bgcolor属性的用法RandomAccessFile randomAccessFile = new RandomAccessFile(savefile, "rw");
randomfile.seek(startext);
while(startext<endtext){
randomAccessFile.adByte());//⽂件写⼊
startext = FilePointer();
}
//关闭各种输⼊输出流
randomAccessFile.close();
randomfile.close();
tempfile.delete();//删除临时⽂件
SimpleDateFormat timed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date nowdate = new Date();
String time = timed.Time());
request.setAttribute("info", time+" "+filename+"上传成功!");
request.setAttribute("filename", filename);
}
}
下载部分
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub
String filename = Parameter("filename");
String path = getServletContext().getRealPath("/")+"images/";
linux容器培训File file = new File(path+filename);//到⽂件
ists())
response.setContentType("application/x-msdownload"); //设置响应类型,此处为下载类型
response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");//以附件的形式打开 InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = OutputStream();
byte b[] = new byte[1024];
int n;
百度爱采购服务商查询while((n = ad(b)) != -1)
{
outputStream.write(b,0,n);
}
outputStream.close();
inputStream.close();
}else{
request.setAttribute("result", "⽂件不存在!下载失败!");
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论