Uploading and downloading files in JSP

Source: Internet
Author: User
Tags rar
1. Client upload file
Client through a JSP page, upload files to the server, the JSP page must contain a file class form, and the form must be set enctype= "Multipart/form-data". An input stream is obtained by Request,request.getinputstream () the built-in object when submitting the form.
When uploading files, there will be additional information, as follows:-----------------------------7d71042a40328
Content-disposition:form-data; Name= "Fileforload"; Filename= "C:/Documents and settings/zj/desktop/book.txt"
Content-type:text/plain
Here is the contents of the file
-----------------------------7d71042a40328
Content-disposition:form-data; Name= "Submit" commit
-----------------------------7d71042a40328--Additional information size is 297 bytes (not determined by this value, tested), available via Request.getcontentlength () > 297来 whether to upload a file or to submit an empty string. 2. Test
FILEUPLOAD.JSP is responsible for submitting files, accept.jsp is responsible for the implementation of upload functions.
fileupload.jsp <meta http-equiv= "Content-type" content= "text/html; charset=gb18030 ">
<title>this page for fileupload</title>
<body>
<p>choose the file for uploading:
<form action= "accept.jsp" Method=post enctype= "Multipart/form-data" >
<input type=file name=fileforload size=30>
<br>
<input Type=submit Value=commit name=submit>
</form>
</body>
<meta http-equiv= "Content-type" content= "text/html; charset=gb18030 ">
<title>this page for response</title>
<body>
<%try{
if (Request.getcontentlength () >297) {
InputStream In=request.getinputstream ();
File F=new file ("D:/temp", "test.txt");
FileOutputStream o=new FileOutputStream (f);
byte b[]=new byte[1024];
int n;
while ((N=in.read (b))!=-1) {
O.write (B,0,n);
}
O.close ();
In.close ();
Out.print ("File upload success!");
}
else{
Out.print ("No file!");
}
}
catch (IOException e) {
Out.print ("Upload error.");
E.printstacktrace ();
}
%>
</body>
Content-disposition:form-data; Name= "Fileforload"; Filename= "C:/Documents and settings/zj/desktop/I like.txt"
Content-type:text/plain I like to ride the code in the lightning to create perfect;
I like to manipulate the code to experience life at my whim;
I like to use the mood code to compile my small difference;
Every new piece of code in my hand Yensen to me like watching the moment flowers open moving;
I don't need the focus, because I'm the focus! -----------------------------7d75b1540328
Content-disposition:form-data; Name= "Submit" commit
-----------------------------7d75b1540328-- 3. Remove additional information
According to the HTTP protocol, the first 4 lines and the last 5 lines in the information submitted by the file form are the information of the form itself, and the middle part is the content of the uploaded file. The following example handles the uploaded file, gets the filename, and removes additional information. 4. Test
fileupload.jsp unchanged, accept.jsp modified as follows: <meta http-equiv= "Content-type" content= "text/html; charset=gb18030 ">
<title>the Real File</title>
<body>
<%try{
Use SessionID to create a temp file.
String Tempfilename= (String) Session.getid ();
Create the temp file.
File Temp=new file ("D:/temp", tempfilename);
FileOutputStream o=new FileOutputStream (temp);
if (Request.getcontentlength () >297) {
Write the upload content to the temp file.
InputStream In=request.getinputstream ();
byte b[]=new byte[1024];
int n;
while ((N=in.read (b))!=-1) {
O.write (B,0,n);
}
O.close ();
In.close ();
Read the temp file.
Randomaccessfile random=new randomaccessfile (temp, "R");
Read Line2 to find the name of the upload file.
int second=1;
String Secondline=null;
while (second<=2) {
Secondline=random.readline ();
second++;
}
Get the last location of the dir char. '//'.
int Position=secondline.lastindexof ('//');
Get the name of the upload file.
String filename=secondline.substring (Position+1,secondline.length ()-1);
Relocate to the head of file.
Random.seek (0);
Get the location's the char. ' Enter ' in Line4.
Long forthendposition=0;
int forth=1;
while ((N=random.readbyte ())!=-1&& (forth<=4)) {
if (n== '/n ') {
Forthendposition=random.getfilepointer ();
forth++;
}
}
File Realfile=new file ("D:/temp", fileName);
Randomaccessfile random2=new randomaccessfile (realfile, "RW");
Locate the end position of the content. Count backwards 6 lines.
Random.seek (Random.length ());
Long Endposition=random.getfilepointer ();
Long mark=endposition;
int j=1;
while ((mark>=0) && (j<=6)) {
mark--;
Random.seek (Mark);
N=random.readbyte ();
if (n== '/n ') {
Endposition=random.getfilepointer ();
j + +;
}
}
Locate to the begin of content. Count for 4 Lines ' s end position.
Random.seek (forthendposition);
Long Startpoint=random.getfilepointer ();
Read the real content and write it to the realfile.
while (startpoint<endposition-1) {
N=random.readbyte ();
Random2.write (n);
Startpoint=random.getfilepointer ();
}
Random2.close ();
Random.close ();
Delete the temp file.
Temp.delete ();
Out.print ("File upload success!");
}
else{
Out.print ("No file!");
}
}
catch (IOException e) {
Out.print ("Upload error.");
E.printstacktrace ();
}
%>
</body>
(Note: If the filename is Chinese, there will be garbled characters.) ) 5. File Download
The JSP built-in object response call Method Getoutputstream () can get an output stream to the customer, the server writes the file to the stream, and then downloads the file. 6. Test
download.jsp Displays the download option and Loadfile.java (Servlet) is responsible for downloading the files.
download.jsp <meta http-equiv= "Content-type" content= "text/html; charset=gb18030 ">
<title>download page</title>
<body>
<a href=loadfile>download:test.zip</a>
</body>
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.OutputStream; Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; @SuppressWarnings ("Serial")
public class LoadFile extends httpservlet{
public void doget (httpservletrequest request,httpservletresponse response)
Throws ioexception,servletexception{
OutputStream O=response.getoutputstream ();
byte b[]=new byte[1024];
The file to download.
File Fileload=new file ("D:/temp", "Test.rar");
The dialogbox of download file.
Response.setheader ("Content-disposition",
"Attachment;filename=" + "Test.rar");
Set the MIME type.
Response.setcontenttype ("Application/x-tar");
Get the file length.
Long Filelength=fileload.length ();
String length=string.valueof (filelength);
Response.setheader ("Content_length", Length);
Download the file.
FileInputStream in=new FileInputStream (fileload);
int n=0;
while ((N=in.read (b))!=-1) {
O.write (B,0,n);
}
}
public void DoPost (httpservletrequest request,httpservletresponse response)
Throws ioexception,servletexception{
Doget (Request,response);
} web.xml (register servlet) <servlet>
<servlet-name>LoadFileServlet</servlet-name>
<servlet-class>com.zj.sample.LoadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoadFileServlet</servlet-name>
<url-pattern>/loadFile</url-pattern>
</servlet-mapping>
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.