Jsp implements file upload and download

Source: Internet
Author: User
Tags save file

I. File Upload

Uploading files is a frequently used function in Web development. For example, uploading photos in the B/S-based personnel information management system and uploading images in the news publishing system ..... To implement the file upload function, you must use the classes related to file input and output in java.

In TCP/IP, the earliest file upload mechanism is FTP. It is a standard mechanism for sending files from the client to the server. It can take into account cross-platform text and binary format files. However, in jsp programming, you cannot use the FTP method to upload files, which is determined by the jsp operating mechanism.

The following is the jsp page for uploading files:

1 <form action = "file? File = upload "method =" post "enctype =" multipart/form-data "> 2. Select the file to be uploaded: <input type = "file" name = "upload" siez = "16"> <br> 3 <input type = "submit" value = "submit"> 4 </form>

 

For File Upload form processing, the method must be post, and the type of enctype = "multipart/form-data" must be added ". In this way, the data in the file can be uploaded as streaming data. Of course, no matter what file format it is, it can be...

Below is the servlet processing program:

1 // receives the file name of the temporary file in the content of the uploaded file. 2 String tempFileName = new String ("tempFileName "); 3 // The tempfile object directs to the temporary File 4 File tempFile = new File ("D:/" + tempFileName ); 5 // The output stream of the outputfile file points to the temporary file 6 FileOutputStream outputStream = new FileOutputStream (tempFile); 7 // get all data submitted by the client 8 InputStream fileSourcel = request. getInputStream (); 9 // write the obtained data to the temporary file 10 byte B [] = new byte [1000]; 11 int n; 12 while (n = fileSourcel. read (B ))! =-1) {13 outputStream. write (B, 0, n); 14} 15 16 // close the output stream and input stream 17 outputStream. close (); 18 fileSourcel. close (); 19 20 // The randomFile object points to the temporary file 21 RandomAccessFile randomFile = new RandomAccessFile (tempFile, "r "); 22 // read the first data row of the temporary file 23 randomFile. readLine (); 24 // read the second row of data of the temporary file. This row contains the file path and file name 25 String filePath = randomFile. readLine (); 26 // get the file name 27 int position = filePath. lastIndexOf ('\'); 28 CodeToString codeToString = New CodeToString (); 29 String filename = codeToString. codeString (filePath. substring (position, filePath. length ()-1); 30 // reposition the read object pointer to the file header 31 randomFile. seek (0); 32 // get the location of the fourth line carriage return, which is the start position of the uploaded file data 33 long forthEnterPosition = 0; 34 int forth = 1; 35 while (n = randomFile. readByte ())! =-1 & (forth <= 4) {36 if (n = '\ n') {37 forthEnterPosition = randomFile. getFilePointer (); 38 forth ++; 39} 40} 41 42 // the directory for generating the uploaded File 43 File fileupLoad = new File ("D: /work space/JSP workspace/jsp_servlet_upAndLoad/file "," upLoad "); 44 fileupLoad. mkdir (); 45 // The saveFile object points to the File to be saved 46 File saveFile = new file ("D:/work space/JSP workspace/jsp_servlet_upAndLoad/File/upLoad ", filename); 47 RandomAccessFile randomAccessFile = new RandomAccessFile (saveFile, "rw"); 48 // locate the end position of the uploaded file data, that is, 49 randomFile in the last row. seek (randomFile. length (); 50 long endPosition = randomFile. getFilePointer (); 51 int j = 1; 52 while (endPosition> = 0) & (j <= 4) {53 endPosition --; 54 randomFile. seek (endPosition); 55 if (randomFile. readByte () = '\ n') {56 j ++; 57} 58} 59 60 // from the start position to the end position of the uploaded file data, write Data to the file to be saved 61 randomFile. seek (forthEnterPosition); 62 long startPoint = randomFile. getFilePointer (); 63 while (startPoint <endPosition) {64 randomAccessFile. write (randomFile. readByte (); 65 startPoint = randomFile. getFilePointer (); 66} 67 // close file input and output 68 randomAccessFile. close (); 69 randomFile. close (); 70 tempFile. delete ();

 

The CodeToString () method is a Chinese character processing method. If the file is not encoded or converted, the uploaded file name will be garbled and the received file data will also be garbled:

The following is the source code of CodeToString:

1 // function 2 public String codeString (String str) {3 String s = str; 4 try {5 byte [] temp = s. getBytes ("UTF-8"); 6 s = new String (temp); 7 return s; 8} catch (UnsupportedEncodingException e) {9 e. printStackTrace (); 10 return s; 11} 12}

 

 

Ii. File Download
The simplest way to download files is to use hyperlinks. Assume that the file "user.doc" is stored in the uploadsubdirectory under the web directory of the server. For example:

<A href = "http: // localhost: 8080/upload/user.doc"> download user.doc </a>

When you click this hyperlink, the document will be opened directly in the browser, just like embedding the wordsoftware in the browser.

After opening the document, you can save it. Of course, on the web, the most common way is to click the link and the "Save as" dialog box appears:

1 // get the file name to download 2 String filename = request. getParameter ("name"); 3 // get the output stream 4 OutputStream outputStream = response. getOutputStream (); 5 // byte array used for the output file. Each time 600 bytes are sent to the output stream, 6 byte B [] = new byte [600]; 7 // File 8 fileload = new File ("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad", filename ); 9 // the "save file" dialog box 10 response. setHeader ("Content-disposition", "attachment; filename =" + filena Me); 11 // notify Customer Service of the MIME type 12 response. setContentType ("application/msword"); 13 // The length of the notification file 14 long fileLength = fileload. length (); 15 String length = String. valueOf (fileLength); 16 response. setHeader ("Content_length", length); 17 // read the file and send it to the client to download 18 FileInputStream inputStream = new FileInputStream (fileload); 19 int n = 0; 20 while (n = inputStream. read (B ))! =-1) {21 outputStream. write (B, 0, n); 22}

 

In this program, the setContentType () of the response object is used to define the MIME type that the server sends to the client content. MIME is not introduced here. In fact, all resources that the browser can process have corresponding MIME resource types. In interaction with the server, the browser directly opens html, jsp, and other file browsers. For files that cannot be opened by browsers such as word and excel, the corresponding method is called. For files that do not mark the MIME type. The browser guesses its type based on its extension and file content...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.