一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - Apache commons fileupload文件上傳實例講解

Apache commons fileupload文件上傳實例講解

2020-06-23 12:49xingoo JAVA教程

這篇文章主要為大家詳細介紹了Apache commons fileupload文件上傳實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下

文件上傳的方法主要目前有兩個常用的,一個是SmartUpload,一個是Apache的Commons fileupload.

我們這里主要介紹下第二個的用法,首先要上傳文件,注意幾個問題:

  1 form表單內,要添加空間<input type="file" name="myfile">

  2 form表單的內容格式要定義成multipart/form-data格式

  3 需要類庫:1 commons-io.jar 2commons-fileupload-1.3.1.jar

接下來我們看下用法。

首先閱讀Apache commons fileupload的官方文檔可以發現下面幾個常用的函數:

1 創建文件解析對象

 

復制代碼 代碼如下:
DiskFileUpload diskFileUpload = new DiskFileUpload();

 

 

2 進行文件解析后放在List中,因為這個類庫支持多個文件上傳,因此把結果會存在List中。

 

復制代碼 代碼如下:
List<FileItem> list = diskFileUpload.parseRequest(request);

 

 

3 獲取上傳文件,進行分析(不是必須)

 

復制代碼 代碼如下:
File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));

 

 

4 創建新對象,進行流拷貝

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file1.getParentFile().mkdirs();
            file1.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }

這樣我們就完成了文件的上傳。

fileUpload.html

 

?
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
<form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
   <div align="center">
     <fieldset style="width:80%">
       <legend>上傳文件</legend><br/>
         <div align="left">上傳文件1</div>
         <div align="left">
           <input type="file" name="file1"/>
         </div>
         <div align="left">上傳文件2</div>
         <div align="left">
           <input type="file" name="file2"/>
         </div>
         <div>
           <div align='left'>上傳文件說明1</div>
           <div align='left'><input type="text" name="description1"/></div>
         </div>
         <div>
           <div align='left'>上傳文件說明2</div>
           <div align='left'><input type="text" name="description2"/></div>
         </div>
         <div>
           <div align='left'>
             <input type='submit' value="上傳文件"/>
           </div>
         </div>
     </fieldset>
   </div>
 </form>

web.xml

?
1
2
3
4
5
6
7
8
<servlet>
  <servlet-name>UploadServlet</servlet-name>
  <servlet-class>com.test.hello.UploadServlet</servlet-class>
 </servlet>
<servlet-mapping>
  <servlet-name>UploadServlet</servlet-name>
  <url-pattern>/servlet/UploadServlet</url-pattern>
 </servlet-mapping>

UploadServlet.java

 

?
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package com.test.hello;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
 
public class UploadServlet extends HttpServlet {
 
  /**
   * Constructor of the object.
   */
  public UploadServlet() {
    super();
  }
 
  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
  }
 
  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    response.setCharacterEncoding("UTF-8");
    response.getWriter().println("請以POST方式上傳文件");
  }
 
  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  @SuppressWarnings({ "unchecked", "deprecation" })
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    File file1 = null,file2=null;
    String description1 = null,description2 = null;
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    
    DiskFileUpload diskFileUpload = new DiskFileUpload();
    try{
      List<FileItem> list = diskFileUpload.parseRequest(request);
      
      out.println("遍歷所有的FileItem...<br/>");
      for(FileItem fileItem : list){
        if(fileItem.isFormField()){
          if("description1".equals(fileItem.getFieldName())){
            out.println("遍歷到description1 ... <br/>");
            description1 = new String(fileItem.getString().getBytes(),"UTF-8");
          }
          if("description2".equals(fileItem.getFieldName())){
            out.println("遍歷到description2 ... <br/>");
            description2 = new String(fileItem.getString().getBytes(),"UTF-8");
          }
        }else{
          if("file1".equals(fileItem.getFieldName())){
            File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
            out.println("遍歷到file1...<br/>");
            out.println("客戶端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
            
            file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file1.getParentFile().mkdirs();
            file1.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file1);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file1.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }
          }
          if("file2".equals(fileItem.getFieldName())){
            File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
            out.println("遍歷到file2...<br/>");
            out.println("客戶端文件位置:"+remoteFile.getAbsolutePath()+"<br/>");
            
            file2 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
            file2.getParentFile().mkdirs();
            file2.createNewFile();
            
            InputStream ins = fileItem.getInputStream();
            OutputStream ous = new FileOutputStream(file2);
            
            try{
              byte[] buffer = new byte[1024];
              int len = 0;
              while((len = ins.read(buffer)) > -1)
                ous.write(buffer,0,len);
              out.println("以保存文件"+file2.getAbsolutePath()+"<br/>");
            }finally{
              ous.close();
              ins.close();
            }
          }
        }
        out.println("Request 解析完畢<br/><br/>");
      }
    }catch(FileUploadException e){}
    
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
    out.println("<HTML>");
    out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
    out.println(" <BODY>");
    
    if(file1 != null){
      out.println("<div>");
      out.println(" <div align='left'>file1;</div>");
      out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
          file1.getName()+"'target=_blank>"+file1.getName()+"</a>");
      out.println("</div>");
      out.println("</div>");
    }
    if(file2 != null){
      out.println("<div>");
      out.println(" <div align='left'>file2;</div>");
      out.println(" <div align='left'><a href='"+request.getContextPath()+"/attachment/"+
          file2.getName()+"'target=_blank>"+file2.getName()+"</a>");
      out.println("</div>");
      out.println("</div>");
    }
    out.println("<div>");
    out.println(" <div align='left'>description1:</div>");
    out.println(" <div align='left'>");
    out.println(description1);
    out.println("</div>");
    out.println("</div>");
    
    out.println("<div>");
    out.println(" <div align='left'>description2:</div>");
    out.println(" <div align='left'>");
    out.println(description2);
    out.println("</div>");
    out.println("</div>");
    
    out.println(" </BODY>");
    out.println("</HTML>");
    out.flush();
    out.close();
  }
 
  /**
   * Initialization of the servlet. <br>
   *
   * @throws ServletException if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }
 
}

運行示例

Apache commons fileupload文件上傳實例講解

Apache commons fileupload文件上傳實例講解

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 成人永久免费 | 波多野结衣之双方调教在线观看 | 国产男女乱淫真视频全程播放 | 99精品国产美女福到在线不卡 | 国产综合成色在线视频 | 涩涩五月天 | 校园春色自拍偷拍 | 国产成人精品免费大全 | 青青草原在线 | 国色天香社区视频免费观看3 | 亚洲精品成人456在线播放 | 天作谜案免费完整版在线观看 | 香蕉久久一区二区不卡无毒影院 | 人人揉人人爽五月天视频 | 2023最新伦理片 | 扒开黑女人p大荫蒂老女人 扒开大腿狠狠挺进视频 | 天堂成人在线观看 | 四虎成人4hutv影院 | 色久激情 | 护士让我吃奶我扒她奶 | 亚洲天堂影视 | 500福利第一巨人导航 | a免费看 | 久久er国产精品免费观看2 | 久久不卡免费视频 | vomoulei成人舞蹈 | 丝袜捆绑调教丨vk | 1024日韩基地 | 日韩精品欧美国产精品亚 | 久久噜国产精品拍拍拍拍 | 日本无遮挡拍拍拍凤凰 | 国产成人高清精品免费5388密 | 欧美肥乳| 国产一区二区精品 | 教室里老师好紧h | 天天操夜夜操狠狠操 | 91久久国产露脸精品 | 成人操 | 国产-第1页-草草影院 | 狠狠躁夜夜躁人人爽天天miya | sxx免费看视频在线播放 |