First, File upload
Uploading files is a frequently used feature in web development: for example, uploading photos in a personnel information management system based on B/s, uploading pictures in a news release system, etc... To implement the file upload function, you need to use the file input and output related classes in Java.
In TCP/IP, the first file upload mechanism that appears is FTP. It is a standard mechanism for sending files from the customer service side to the server, allowing for cross-platform text and binary format files. However, in JSP programming can not use the FTP method to upload files, which is determined by the JSP operating mechanism.
Here is the JSP page to upload the file:
[HTML]View Plaincopyprint? < param name= "allowfullscreen" value= "false" >< param name= "wmode" value= "Transparent" >
- <form action="file?file=upload" method="POST" enctype="Multipart/form-data " >
- Please select the file you want to upload:<input type="file" name= "upload" siez= "+" >< br>
- <input type="Submit" value= "submission">
- </form>
[HTML]View Plaincopyprint?
For file Upload form processing where method must be post, also add type enctype= "Multipart/form-data". This allows the data in the file to be uploaded as streaming data. Of course, no matter what the file format, can ...
The following is a servlet handler:
[Java]View Plaincopyprint?
- //Receive file name of temporary files in upload file contents
- String tempfilename = new String ("TempFileName");
- Tempfile object pointing to a temporary file
- File Tempfile = new File ("d:/" +tempfilename);
- OutputFile file output stream points to this temporary file
- FileOutputStream outputstream = new FileOutputStream (tempfile);
- Get all the data submitted by the client
- InputStream filesourcel = Request.getinputstream ();
- Writes the resulting client data to a temporary file
- byte b[] = new byte[1000];
- int n;
- while ((N=filesourcel.read (b))!=-1) {
- Outputstream.write (b,0,n);
- }
- Turn off the output stream and input stream
- Outputstream.close ();
- Filesourcel.close ();
- Randomfile object pointing to a temporary file
- Randomaccessfile randomfile = new Randomaccessfile (Tempfile,"R");
- Reads the first row of data from a temporary file
- Randomfile.readline ();
- Reads the second row of data from the temporary file, which contains the path and file name of the files
- String FilePath = Randomfile.readline ();
- Get file name
- int position = filepath.lastindexof (' \ \ ');
- Codetostring codetostring = new codetostring ();
- String filename = codetostring.codestring (filepath.substring (Position,filepath.length ()-1));
- Reposition read file pointer to file header
- Randomfile.seek (0);
- Gets the position of the four-row carriage return, which is the beginning of the upload file data
- Long forthenterposition = 0;
- int forth = 1;
- while ((N=randomfile.readbyte ())!=-1&& (forth<=4)) {
- if (n==' \ n ') {
- Forthenterposition = Randomfile.getfilepointer ();
- forth++;
- }
- }
- Generate directory for uploaded files
- File FileupLoad = new File ("D:/work space/jsp workspace/jsp_servlet_upandload/file","upLoad");
- Fileupload.mkdir ();
- The SaveFile object points 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");
- Find the end location of the uploaded file data, which is the fourth line
- 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 + +;
- }
- }
- Writes data to the file to be saved from the beginning of the uploaded file data to the end location
- Randomfile.seek (forthenterposition);
- Long startPoint = Randomfile.getfilepointer ();
- while (startpoint<endposition) {
- Randomaccessfile.write (Randomfile.readbyte ());
- StartPoint = Randomfile.getfilepointer ();
- }
- Close file input, output
- Randomaccessfile.close ();
- Randomfile.close ();
- Tempfile.delete ();
where the Codetostring () method is a Chinese character processing method. If the file does not encode the conversion, the uploaded file name will be garbled, the received data will be garbled:
Here is the codetostring () source code:
[Java]View Plaincopyprint?
- Functions for handling 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;
- }
- }
Two: File download the simplest way to implement a file download is to use a hyperlink. Suppose User.doc This document exists in the upload subdirectory of the Web directory on the server. Such as:
[Java]View Plaincopyprint?
- <a href="Http://localhost:8080/upload/user.doc" > Download user.doc</a>
When you click the hyperlink, the document opens directly in the browser, as if you were embedding the word software in a browser.
When you open a document, you can save it. Of course, on the web, the most common way is when you click the link and the Save As dialog box appears:
[Java]View Plaincopyprint?
- Get the file name to download
- String filename = request.getparameter ("name");
- //Get the output stream to the customer
- OutputStream outputstream = Response.getoutputstream ();
- //output file with byte array, send 600 bytes to the output stream at a time
- byte b[] = new byte[600];
- //files to download
- File Fileload = new File ("D:/work space/jsp workspace/jsp_servlet_upandload/file/upload", filename);
- //client Use the Save File dialog box
- Response.setheader ("content-disposition", "attachment;filename=" +filename);
- //Notify the MIME type of the customer service file
- Response.setcontenttype ("Application/msword");
- //Inform the length of customer service file
- Long filelength = Fileload.length ();
- String length = string.valueof (filelength);
- Response.setheader ("content_length", length);
- //Read files, and send to the customer service side 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 defines the MIME type that the server sends to the client side of the content. This is not a special introduction to MIME. In fact, all resources that the browser can handle have a corresponding MIME resource type. In the interaction with the server, the browser opens it directly to the HTML, JSP, and other file browsers. The appropriate method is called for files that cannot be opened by browsers such as Word, Excel, and so on. For files that do not have a tag MIME type. The browser guesses its type based on its extension and file content ...