对于JSP的知识总结,已经为大家分享的差不多了,本篇就为大家做一下最后总结,本篇总结的主题是文件上传和下载,在之前的随笔中也有为大家分享过文件上传和下载的知识,不过都是通过JAVA提供的上传下载类实现的,本篇将通过文件输入输出流的方式为大家精讲一下文件的上传和下载实现,我相信当你了解了底层的实现后,会很方便你对于文件的上传和下载进行拓展。好了废话不多说,下面我们开始本篇的总结。
1、上传分析:
文件上传就是,我们通过Form表单中的input属性,向后台发送用户需要上传的文件,后台当发现用户发送的请求后,首先将用户上传的文件保存到一个临时文件中,为接下来我们获取上传文件名和上传文件内容做准备。
2、jsp页面要求:
form的method="post"一定要设置为post方式,因为get方式传输,首先他是一种不安全的传输,其次它传输的内容大小有限,不能传输大量的数据。然后我们要修改enctype="multipart/form-data",默认值为:application/x-www-form-urlencoded。具体的代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>上传文件</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <h1>文件上传</h1> <form action="<%=request.getContextPath() %>/servlet/ShangChuan" method="post" enctype="multipart/form-data"> 选择上传文件:<input type="file" name="file" id="file"/><input type="submit" value="上传"><span style="color: red">${news }</span> </form> </center> </body> </html>
3、后台servlet:
第一步:把用户上传的文件保存的一个临时文件
InputStream fileSource = request.getInputStream(); String tempFileName = "F:/cnblogs/text"; File tempFile = new File(tempFileName); FileOutputStream outputStream = new FileOutputStream(tempFile); byte [] b = new byte[2048]; int n; while((n = fileSource.read(b))!=-1){ outputStream.write(b, 0, n); } //关闭输入、输出流 outputStream.flush(); outputStream.close(); fileSource.close();
第二步:通过获取临时文件中的内容来捕获用户上传文件的名字和内容区域的位置
//获取上传文件的名称 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); System.out.println("fileName:"+fileName); //重新定位文件指针到文件头 randomFile.seek(0); long startPosition = 0; int i = 1; //获取文件内容开始位置 while((n=randomFile.readByte())!=-1&&i<=4){ if(n==' '){ startPosition = randomFile.getFilePointer(); i++; } } startPosition = startPosition-1; //获取文件内容到结束位置 randomFile.seek(randomFile.length()); long endPosition = randomFile.getFilePointer(); int j = 1; while(endPosition>=0&&j<=2){ endPosition--; randomFile.seek(endPosition); if(randomFile.readByte()==' '){ j++; } } endPosition = endPosition-1; //设置保存文件的路径 String realPath = getServletContext().getRealPath("/")+"images"; File fileupload = new File(realPath); if(!fileupload.exists()){ fileupload.mkdir(); } File saveFile = new File(realPath, fileName); RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile, "rw"); //从临时文件当中读取文件内容(根据起止位置获取) randomFile.seek(startPosition); while(startPosition<endPosition){ randomAccessFile.write(randomFile.readByte()); startPosition = randomFile.getFilePointer(); } //关闭输入、输出流,删除临时文件 randomAccessFile.close(); randomFile.close(); tempFile.delete(); request.setAttribute("news", "文件上传成功"); request.getRequestDispatcher("/index.jsp").forward(request, response);
这里是通过String类的LastIndexOf()方法和subString()方法来获得我们需要的内容。到这里我们的上传就实现了,下面我们来一起学习一下下载的工程。
4、下载的JSP页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>文件下载</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <h1>文件下载操作</h1> <a href="<%=request.getContextPath() %>/servlet/download?filename=text.txt" >Text.txt</a><span style="color: red">${news }</span> </center> </body> </html>
5、后台servlet:
public class download extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取文件下载路径 String path = getServletContext().getRealPath("/")+"images/"; String filename = request.getParameter("filename"); File file = new File(path+filename); if(file.exists()){ //设置相应的类型 response.setContentType("application/x-msdownload"); //设置头信息 response.setHeader("content-Disposition", "attachment;filename=""+filename+"""); InputStream input = new FileInputStream(file); ServletOutputStream output = response.getOutputStream(); byte[] b = new byte[2048]; int n; while((n=input.read(b))!=-1){ output.write(b, 0, n); } //关闭流对象 output.close(); input.close(); }else{ request.setAttribute("news", "文件不存在,下载失败。"); request.getRequestDispatcher("/MyJsp.jsp").forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
这下我们的文件上传和下载已经实现了,当然这些都是最基本的东西,大家可以发挥自己脑力进行拓展,到今天关于JSP的总结为大家分享完毕了,大家如有疑问请留言讨论。