JSP implementation File Upload Download program Example _jsp programming

Source: Internet
Author: User
Tags readline first row

First, File upload
Uploading files is a feature that is often used in web development: for example, uploading photos in the HR information Management system based on B/s, uploading pictures in the news release system and so on. To implement the file upload function, it is necessary to comprehensively utilize the file input and output related classes in Java.
In TCP/IP, the first occurrence of the file upload mechanism is FTP. It is a standard mechanism for sending files from a customer service to the server, taking into account cross-platform text and binary format files. But in JSP programming can not use FTP method to upload files, this is the JSP operating mechanism decided.
The following is a JSP page for uploading files:

Copy Code code as follows:

<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= "submitted" >
</form>

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 file format, can be ...
The following is a servlet handler:

Copy Code code as follows:

Receive the file name of the temporary file in the uploaded file content
String tempfilename = new String ("TempFileName");
The Tempfile object points to a temporary file
File Tempfile = new file ("d:/" +tempfilename);
The OutputFile file output stream points to this temporary file
FileOutputStream outputstream = new FileOutputStream (tempfile);
Get all the data submitted by customer service
InputStream filesourcel = Request.getinputstream ();
Write 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 the input stream
Outputstream.close ();
Filesourcel.close ();

The Randomfile object points to a temporary file
Randomaccessfile randomfile = new Randomaccessfile (tempfile, "R");
Read the first row of data from a temporary file
Randomfile.readline ();
Reads the second row of data in the temporary file, which contains the path and file name of the file
String FilePath = Randomfile.readline ();
Get file name
int position = Filepath.lastindexof (' \ n ');
codetostring codetostring = new codetostring ();
String filename = codetostring.codestring (filepath.substring (Position,filepath.length ()-1));
Relocate read file pointer to file header
Randomfile.seek (0);
Gets the position of the four-line carriage return, which is the starting 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++;
}
}

Create a 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 save
File SaveFile = new file ("D:/work space/jsp workspace/jsp_servlet_upandload/file/upload", filename);
Randomaccessfile randomaccessfile = new Randomaccessfile (SaveFile, "RW");
Find the ending position of the uploaded file data, that is, line fourth
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 position
Randomfile.seek (forthenterposition);
Long startpoint = Randomfile.getfilepointer ();
while (startpoint<endposition) {
Randomaccessfile.write (Randomfile.readbyte ());
StartPoint = Randomfile.getfilepointer ();
}
Turn off 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 conversion, the uploaded file name will be garbled, receive the file data will also be garbled:
The following is the codetostring () source code:

Copy Code code as follows:

Functions to handle 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;
}
}

Second: File download

The easiest way to implement a file download is to use a hyperlink. This document is assumed to exist in the upload subdirectory of the Web directory on the server User.doc. Such as:
<a href= "Http://localhost:8080/upload/user.doc" > Download user.doc</a>
When you click the hyperlink, you will open the document directly in your browser, as if you were embedding Word software in your browser.
After you open the document, you can implement the Save As. Of course on the web, the most common way is to click the link and the Save As dialog box appears:

Copy Code code as follows:

Get the file name to download
String filename = request.getparameter ("name");
Get the output stream that you want the client to output
OutputStream outputstream = Response.getoutputstream ();
An array of bytes for the output file, sending 600 bytes at a time to the output stream
byte b[] = new byte[600];
Files to download
File Fileload = new file ("D:/work space/jsp workspace/jsp_servlet_upandload/file/upload", filename);
Customer Service uses a dialog box to save the file
Response.setheader ("Content-disposition", "attachment;filename=" +filename);
Notify customer service of MIME type of file
Response.setcontenttype ("Application/msword");
Inform customer service of the length of the file
Long filelength = Fileload.length ();
String length = string.valueof (filelength);
Response.setheader ("content_length", length);
Read the file and send it to the customer service side 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 response object's setContentType () is used to define the MIME type that the server sends to the customer service side. MIME is not specifically described here. In fact, all the resources that a browser can handle have a corresponding MIME resource type. In the interaction with the server, the browser is the HTML, JSP and other file browsers to open it directly. Call the appropriate method for files that cannot be opened by browsers such as Word, Excel, and so on. For files that do not have a MIME type marked. The browser guesses its type based on its extension and file contents ...

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.