對于JSP的知識總結,已經為大家分享的差不多了,本篇就為大家做一下最后總結,本篇總結的主題是文件上傳和下載,在之前的隨筆中也有為大家分享過文件上傳和下載的知識,不過都是通過java提供的上傳下載類實現的,本篇將通過文件輸入輸出流的方式為大家精講一下文件的上傳和下載實現,我相信當你了解了底層的實現后,會很方便你對于文件的上傳和下載進行拓展。好了廢話不多說,下面我們開始本篇的總結。
1、上傳分析:
文件上傳就是,我們通過Form表單中的input屬性,向后臺發送用戶需要上傳的文件,后臺當發現用戶發送的請求后,首先將用戶上傳的文件保存到一個臨時文件中,為接下來我們獲取上傳文件名和上傳文件內容做準備。
2、jsp頁面要求:
form的method="post"一定要設置為post方式,因為get方式傳輸,首先他是一種不安全的傳輸,其次它傳輸的內容大小有限,不能傳輸大量的數據。然后我們要修改enctype="multapplication/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="Words" 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:/VEVb/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=='/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()=='/n'){ 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的總結為大家分享完畢了,大家如有疑問請留言討論。
新聞熱點
疑難解答