转载自:http://www.cnblogs.com/goodwin/archive/2010/09/28/1837387.html

实现文件上传,表单属性需要设置为method=”post”,encType=multipart/form-data,在服务器端通过request.getInputStream()获得文件输入流,然后对流进行操作,获得所需要的内容。

 

 

Html页面代码upload.html

1
2
3
4
< form  action="UploadServlet3" method="post" enctype="multipart/form-data">
     < input  type="file" name="file">
     < input  type="submit" name="upload"value="上传">
</ form >

1.实现基本文件上传

Servlet代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public  class  UploadServlet1 extends  HttpServlet {
     private  static  final  long  serialVersionUID = 1L;
 
     protected  void  doPost(HttpServletRequest request, HttpServletResponseresponse) throws  ServletException, IOException {
 
            InputStream in = request.getInputStream();
            File f = new  File( "d:/temp" , "aaa.txt" );
            FileOutputStream fos = new  FileOutputStream(f);
 
            byte [] b = new  byte [ 1024 ];
            int  n= 0 ;
 
            while ((n=in.read(b))!=- 1 ){
               fos.write(b, 0 ,n);
            }
 
            fos.close();
            in.close();
 
     }
 
}

 

此方法上传的文件打开后如下:

-----------------------------26962244645705

Content-Disposition: form-data; name="file";filename="a.txt"

Content-Type: text/plain

 

Java Servlet Technology

As soon as the web began to be used for deliveringservices, service providers recognized the need for dynamic content. Applets,one of the earliest attempts toward this goal, focused on using the clientplatform to deliver dynamic user experiences. At the same time, developers alsoinvestigated using the server platform for this purpose. Initially, CommonGateway Interface (CGI) scripts were the main technology used to generatedynamic content. Although widely used, CGI scripting technology has a number ofshortcomings, including platform dependence and lack of scalability. To addressthese limitations, Java Servlet technology was created as a portable way toprovide dynamic, user-oriented content.

-----------------------------26962244645705

Content-Disposition: form-data; name="upload"

 

上传

-----------------------------26962244645705--

此处有一个回车符

前面4行和后面6行是表单的一些属性,是默认加入的。

 

2.出去文件流中的多余内容(只支持ie)

UploadServlet2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public  class  UploadServlet2 extends  HttpServlet {
     private  static  final  long  serialVersionUID = 1L;
 
     protected  void  doPost(HttpServletRequest request,
             HttpServletResponse response) throws  ServletException, IOException {
         String tempFileName = (String) request.getSession().getId();
         // create the tempfile.
         File temp = new  File( "d:/temp" , tempFileName);
         FileOutputStream o = new  FileOutputStream(temp);
         if  (request.getContentLength() > 297 ) {
             // write theupload 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 tempfile.
             RandomAccessFile random = new  RandomAccessFile(temp, "r" );
             // read Line2 tofind the name of the upload file.
             int  second = 1 ;
             String secondLine = null ;
             while  (second <= 2 ) {
                 secondLine = random.readLine();
                 second++;
             }
 
             // get the lastlocation of the dir char.'\\'.
             int  position = secondLine.lastIndexOf( '\\' );
             // get the nameof the upload file.
             String fileName = secondLine.substring(position + 1 ,
                     secondLine.length() - 1 );
             // relocate tothe head of file.
             random.seek( 0 );
             // get thelocation of 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 endposition 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 thebegin of content.Count for 4 lines's end position.
             random.seek(forthEndPosition);
             long  startPoint = random.getFilePointer();
             // read the realcontent 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 tempfile.
             temp.delete();
             System.out.println( "File uploadsuccess!" );
         } else  {
             System.out.println( "Nofile!" );
         }
 
     }
 
}