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:
Copy codeThe Code is as follows:
<Form action = "file? File = upload "method =" post "enctype =" multipart/form-data ">
Select the file you want to upload: <input type = "file" name = "upload" siez = "16"> <br>
<Input type = "submit" value = "submit">
</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:
Copy codeThe Code is as follows:
// Receives the file name of the temporary file in the uploaded file content
String tempFileName = new String ("tempFileName ");
// Point the tempfile object to a temporary file
File tempFile = new File ("D:/" + tempFileName );
// Outputfile the output stream points to this temporary file
FileOutputStream outputStream = new FileOutputStream (tempFile );
// Obtain all data submitted by the customer service.
InputStream fileSourcel = request. getInputStream ();
// Write the obtained client data to a temporary file
Byte B [] = new byte [1000];
Int n;
While (n = fileSourcel. read (B ))! =-1 ){
OutputStream. write (B, 0, n );
}
// Close the output stream and input stream
OutputStream. close ();
FileSourcel. close ();
// The randomFile object directs to the temporary file
RandomAccessFile randomFile = new RandomAccessFile (tempFile, "r ");
// Read the first row of data in the temporary file
RandomFile. readLine ();
// Read the second row of data of the temporary file, which contains the file path and file name
String filePath = randomFile. readLine ();
// Get the file name
Int position = filePath. lastIndexOf ('\\');
CodeToString codeToString = new CodeToString ();
String filename = codeToString. codeString (filePath. substring (position, filePath. length ()-1 ));
// Locate and read the file pointer to the file header
RandomFile. seek (0 );
// Get the location of the fourth line carriage return, which is the start position of the uploaded file data
Long forthEnterPosition = 0;
Int forth = 1;
While (n = randomFile. readByte ())! =-1 & (forth <= 4 )){
If (n = '\ n '){
ForthEnterPosition = randomFile. getFilePointer ();
Forth ++;
}
}
// Generate the directory of the uploaded file
File fileupLoad = new File ("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file", "upLoad ");
FileupLoad. mkdir ();
// The saveFile object directs to the file to be saved.
File saveFile = new File ("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad", filename );
RandomAccessFile randomAccessFile = new RandomAccessFile (saveFile, "rw ");
// Locate the end position of the uploaded file data, that is, the last and fourth rows.
RandomFile. seek (randomFile. length ());
Long endPosition = randomFile. getFilePointer ();
Int j = 1;
While (endPosition> = 0) & (j <= 4 )){
EndPosition --;
RandomFile. seek (endPosition );
If (randomFile. readByte () = '\ n '){
J ++;
}
}
// Write data to the file to be saved from the start position to the end position of the uploaded file data
RandomFile. seek (forthEnterPosition );
Long startPoint = randomFile. getFilePointer ();
While (startPoint <endPosition ){
RandomAccessFile. write (randomFile. readByte ());
StartPoint = randomFile. getFilePointer ();
}
// Close file input and output
RandomAccessFile. close ();
RandomFile. close ();
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:
Copy codeThe Code is as follows:
// Functions that process Chinese strings
Public String codeString (String str ){
String s = str;
Try {
Byte [] temp = s. getBytes ("UTF-8 ");
S = new String (temp );
Return s;
} Catch (UnsupportedEncodingException e ){
E. printStackTrace ();
Return s;
}
}
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:
Copy codeThe Code is as follows:
// Get the file name to download
String filename = request. getParameter ("name ");
// Obtain the output stream of the desired client.
OutputStream outputStream = response. getOutputStream ();
// The byte array used for the output file. Each time 600 bytes are sent to the output stream
Byte B [] = new byte [600];
// The object to be downloaded
File fileload = new File ("D:/work space/JSP workspace/jsp_servlet_upAndLoad/file/upLoad", filename );
// Dialog box for saving files on the client
Response. setHeader ("Content-disposition", "attachment; filename =" + filename );
// Notify Customer Service of the MIME type of the file
Response. setContentType ("application/msword ");
// Inform Customer Service of the file length
Long fileLength = fileload. length ();
String length = String. valueOf (fileLength );
Response. setHeader ("Content_length", length );
// Read the file and send it to the client for download.
FileInputStream inputStream = new FileInputStream (fileload );
Int n = 0;
While (n = inputStream. read (B ))! =-1 ){
OutputStream. write (B, 0, n );
}
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...