Java文件上传下载
Posted thegcc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java文件上传下载相关的知识,希望对你有一定的参考价值。
基于Java文件输入输出流的文件上传下载功能实现
原理: 前端通过form表单的enctype属性,将数据传递方式修改为二进制”流“的形式,服务端(servlet)通过 getInputStream() 获取流信息, 运用java I/O 流的基础操作将流写入到一个服务端临时创建的文件temp中,然后再次利用文件基本操作,读取并截取临时文件内容,根据其中信息创建相应的文件,将读取出来的具体信息写入,下载时,根据提交的文件名称,找到服务器端相应的文件,然后根据输出流outStream输出到页面,同时将servlet的响应类型和响应头进行设置。
具体传输流程如下图:
流信息的部分为:
具体代码如下:
前端代码:
1 <html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 4 <title>Insert title here</title> 5 <script src="Js/jquery.js"></script> 6 </head> 7 <body> 8 <form action="FileUpServlet" method="post" enctype="multipart/form-data"> 9 <table> 10 <tr> 11 <td>请选择上传文件:</td><td><input id="myfile" name="myfile" type="file" value="" /></td> 12 <td><input type="submit" value="上传"></td> 13 </tr> 14 <tr><td>${info}</td></tr> 15 </table> 16 </form> 17 文件下载:<a href="FileLoadownServlet?filename=${filename}">${filename}</a> 18 </body> 19 </html>
上传servlet部分(核心)
1 @WebServlet("/FileUpServlet") 2 public class FileUpServlet extends HttpServlet { 3 private static final long serialVersionUID = 1L; 4 5 /** 6 * @see HttpServlet#HttpServlet() 7 */ 8 public FileUpServlet() { 9 super(); 10 // TODO Auto-generated constructor stub 11 } 12 13 /** 14 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 15 */ 16 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 // TODO Auto-generated method stub 18 doPost(request, response); 19 } 20 21 /** 22 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 23 */ 24 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 25 // TODO Auto-generated method stub 26 request.setCharacterEncoding("utf-8"); 27 InputStream filesource = request.getInputStream();//request获取流信息 28 String tempname = "D:/temp";//tempfile代表临时存放文件 29 File tempfile = new File(tempname);//创建临时文件 30 31 FileOutputStream outputStream = new FileOutputStream(tempfile);//输出流对象,指定输出指tempfile目录下 32 byte b[] = new byte[1024]; 33 int n; 34 while((n = filesource.read(b))!= -1)//从输出流中每次读取1024字节,直至读完 35 { 36 outputStream.write(b,0,n); 37 } 38 outputStream.close(); 39 filesource.close();//关闭输入输出流 40 41 42 /*以下为具体的文件操作,主要为解析临时产生的 temp文件 ,知识多为java输入输出流的内容!*/ 43 44 45 RandomAccessFile randomfile = new RandomAccessFile(tempfile, "r");//随机流,指定要读临时文件,只读 46 randomfile.readLine();//读取第一行,无效数据,不需要 47 String str = randomfile.readLine();//读取第二行 48 int beginIndex = str.lastIndexOf("=")+2;//指定所需数据的开始位置 49 int endIndex = str.lastIndexOf("\\"");//指定所需数据截至位置 50 String filename = str.substring(beginIndex,endIndex);//截取文件名 51 52 //重新定位文件指针,获取文件内容 53 randomfile.seek(0);//文件指针从头开始 54 long startext = 0; 55 int i = 1; 56 //文件内容开始位置 57 while((n=randomfile.readByte()) != -1&&i <= 4) 58 { 59 if(n==‘\\n‘) 60 { 61 startext = randomfile.getFilePointer(); 62 i++; 63 } 64 } 65 startext = randomfile.getFilePointer() - 1; 66 //获取文件内容 结束位置 67 randomfile.seek(randomfile.length()); 68 long endtext = randomfile.getFilePointer(); 69 int j = 1; 70 while(endtext >= 0 && j <= 2) 71 { 72 endtext--; 73 randomfile.seek(endtext); 74 if(randomfile.readByte()==‘\\n‘) 75 { 76 j++; 77 } 78 } 79 endtext = endtext-1; 80 81 //将临时文件保存至指定目录中 82 String realpath = getServletContext().getRealPath("/")+"images";//设置文件保存目录 83 System.out.println(realpath); 84 File fileupload = new File(realpath); 85 if(!fileupload.exists()) 86 { 87 fileupload.mkdir();//目录不存在则创建 88 } 89 File savefile = new File(realpath,filename); 90 RandomAccessFile randomAccessFile = new RandomAccessFile(savefile, "rw"); 91 randomfile.seek(startext); 92 while(startext<endtext){ 93 randomAccessFile.write(randomfile.readByte());//文件写入 94 startext = randomfile.getFilePointer(); 95 } 96 //关闭各种输入输出流 97 randomAccessFile.close(); 98 randomfile.close(); 99 tempfile.delete();//删除临时文件 100 101 102 SimpleDateFormat timed = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 103 Date nowdate = new Date(); 104 String time = timed.format(nowdate.getTime()); 105 request.setAttribute("info", time+" "+filename+"上传成功!"); 106 request.setAttribute("filename", filename); 107 request.getRequestDispatcher("/fildeOp.jsp").forward(request, response); 108 } 109 110 }
下载部分
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 // TODO Auto-generated method stub 3 String filename = request.getParameter("filename"); 4 String path = getServletContext().getRealPath("/")+"images/"; 5 File file = new File(path+filename);//找到文件 6 if(file.exists()) 7 { 8 response.setContentType("application/x-msdownload"); //设置响应类型,此处为下载类型 9 response.setHeader("Content-Disposition", "attachment;filename=\\""+filename+"\\"");//以附件的形式打开 10 InputStream inputStream = new FileInputStream(file); 11 ServletOutputStream outputStream = response.getOutputStream(); 12 byte b[] = new byte[1024]; 13 int n; 14 while((n = inputStream.read(b)) != -1) 15 { 16 outputStream.write(b,0,n); 17 } 18 outputStream.close(); 19 inputStream.close(); 20 }else{ 21 request.setAttribute("result", "文件不存在!下载失败!"); 22 request.getRequestDispatcher("/fildeOp.jsp").forward(request, response); 23 } 24 }