Java实现文件上传下载功能 基于Java文件输入输出流实现文件上传下载功能
糖拌西红柿 人气:0本文为大家分享了Java实现文件上传下载功能的具体代码,供大家参考,具体内容如下
前端通过form表单的enctype属性,将数据传递方式修改为二进制”流“的形式,服务端(servlet)通过 getInputStream() 获取流信息, 运用java I/O 流的基础操作将流写入到一个服务端临时创建的文件temp中,然后再次利用文件基本操作,读取并截取临时文件内容,根据其中信息创建相应的文件,将读取出来的具体信息写入,下载时,根据提交的文件名称,找到服务器端相应的文件,然后根据输出流outStream输出到页面,同时将servlet的响应类型和响应头进行设置。
具体传输流程如下图:
流信息的部分为:
具体代码如下:
前端代码:
<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部分(核心)
@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); } }
下载部分
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); } }
加载全部内容