Summary of JSP website development 14 and website development 14
The summary of JSP knowledge has been shared almost for you. This article will give you a final summary. The topic of this article is file upload and download, I have also shared the file upload and download knowledge in my previous articles. However, they are all implemented through the upload and download classes provided by JAVA, this article describes how to upload and download files through the file input and output stream. I believe that when you understand the underlying implementation, you can easily upload and download files. Now let's start with the summary in this article.
1. Upload analysis:
File Upload is to send the file to be uploaded to the background through the input attribute in the Form. After a user sends a request in the background, first, save the uploaded file to a temporary file to prepare for getting the uploaded file name and content.
2. jsp page requirements:
Form's method = "post" must be set to the post mode, because the get mode is transmitted, first it is an insecure transmission, and second it has limited content size, A large amount of data cannot be transmitted. Then, modify enctype = "multipart/form-data". The default value is application/x-www-form-urlencoded. Specific Code:
<% @ 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">
3. backend servlet:
Step 1: Save a temporary file for the user-uploaded file
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);} // close the input and output streams outputStream. flush (); outputStream. close (); fileSource. close ();
Step 2: capture the name and content location of the uploaded file by obtaining the content in the temporary file
// Obtain the name of the uploaded file 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); // reposition the file pointer to the file header randomFile. seek (0); long startPosition = 0; int I = 1; // get the start position of the file content wh Ile (n = randomFile. readByte ())! =-1 & I <= 4) {if (n = '\ n') {startPosition = randomFile. getFilePointer (); I ++ ;}} startPosition = startPosition-1; // get the file content to the end position 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; // set the path to save the file String realPath = get ServletContext (). getRealPath ("/") + "images"; File fileupload = new File (realPath); if (! Fileupload. exists () {fileupload. mkdir ();} File saveFile = new File (realPath, fileName); RandomAccessFile randomAccessFile = new RandomAccessFile (saveFile, "rw "); // read the file content from the temporary file (obtained based on the start position and end position) randomFile. seek (startPosition); while (startPosition <endPosition) {randomAccessFile. write (randomFile. readByte (); startPosition = randomFile. getFilePointer ();} // close the input and output streams and delete the temporary file randomAccessFile. close (); randomFile. close (); tempFile. delete (); request. setAttribute ("news", "File Uploaded successfully"); request. getRequestDispatcher ("/index. jsp "). forward (request, response );
Here we use the LastIndexOf () method and subString () method of the String class to obtain the content we need. Now we have implemented the upload function. Next, let's take a look at the download project.
4. The downloaded JSP page:
<% @ 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">
5. backend servlet:
Public class download extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// get the file download path String path = getServletContext (). getRealPath ("/") + "images/"; String filename = request. getParameter ("filename"); File file = new File (path + filename); if (file. exists () {// set the corresponding type response. setContentType ("application/x-msdownload "); // Set the header information 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);} // close the stream object output. close (); input. close ();} else {request. setAttribute ("news", "the file does not exist. Download failed. "); Request. getRequestDispatcher ("/MyJsp. jsp "). forward (request, response) ;}} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
Now our file upload and download have been implemented. Of course, these are the most basic things. You can use your own resources to expand them. Now we have shared the summary of JSP, if you have any questions, please leave a message for discussion.