javarequest文件上傳
文件上傳就是將客戶端資源,通過網路傳遞到伺服器端。
因為文件數據比較大,必須通過文件上傳才可以完成將數據保存到資料庫端的操作。
文件上傳的本質就是IO流操作。
演示:文件上傳應該如何操作?
瀏覽器端:
1.method=post 只有post才可以攜帶大數據
2.必須使用<input type='file' name='f'>要有name屬性
3.encType="multipart/form-data"
伺服器端:
request對象是用於獲取請求信息。
它有一個方法 getInputStream(); 可以獲取一個位元組輸入流,通過這個流,可以讀取到
所有的請求正文信息.
文件上傳原理:
瀏覽器端注意上述三件事,在伺服器端通過流將數據讀取到,在對數據進行解析.
將上傳文件內容得到,保存在伺服器端,就完成了文件上傳。
注意:在實際開發中,不需要我們進行數據解析,完成文件上傳。因為我們會使用文件上傳的工具,它們已經封裝好的,提供API,只要調用它們的API就可以完成文件上傳操作.我們使用的commons-fileupload,它是apache提供的一套開源免費的文件上傳工具。
代碼演示文件上傳的原理:
在WebRoot下新建upload1.jsp
[html]view plain
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>MyJSP'index.jsp'startingpage</title>
</head>
<body>
<!--encType默認是application/x-www-form-urlencoded-->
<formaction="${pageContext.request.contextPath}/upload1"
method="POST"enctype="multipart/form-data">
<inputtype="text"name="content"><br>
<inputtype="file"name="f"><br><inputtype="submit"
value="上傳">
</form>
</body>
</html>
packagecn.itcast.web.servlet;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//System.out.println("upload1servlet......");
//通過request獲取一個位元組輸入流,將所有的請求正文信息讀取到,列印到控制台
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=-1;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}
is.close();
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
在web頁面中添加上傳輸入項。
在Servlet中讀取上傳文件的數據,並保存在伺服器硬碟中。
1、必須設置input輸入項的name屬性,否則瀏覽器將不會發送上傳文件的數據。
2、必須把form的encType屬性設為multipart/form-data 設置該值後,瀏覽器在上傳文件時,並把文件數據附帶在http請求消息體內,並使用MIME協議對上傳的文件進行描述,以方便接收方對上傳數據進行解析和處理。
3、表單的提交方式要設置為post。
Request對象提供了一個getInputStream方法,通過這個方法可以讀取到客戶端提交過來的數據。但由於用戶可能會同時上傳多個文件,在servlet端編程直接讀取上傳數據,並分別解析出相應的文件數據是一項非常麻煩的工作,示例。
為方便用戶處理文件上傳數據,Apache 開源組織提供了一個用來處理表單文件上傳的一個開源組件( Commons-fileupload ),該組件性能優異,並且其API使用極其簡單,可以讓開發人員輕松實現web文件上傳功能,因此在web開發中實現文件上傳功能,通常使用Commons-fileupload組件實現。
使用Commons-fileupload組件實現文件上傳,需要導入該組件相應支撐jar包:Commons-fileupload和commons-io。commo-io不屬於文件上傳組件的開發jar文件,但Commons-fileupload組件從1.1版本開始,它工作時需要commons-io包的支持。
新建Upload1Servlet 路徑:/upload1
[java]view plain
在瀏覽器端訪問信息如下:
文件上傳概述
實現web開發中的文件上傳功能,需要完成如下二步操作:
如何在web頁面中添加上傳輸入項?
<input type="file">標簽用於在web頁面中添加文件上傳輸入項,設置文件上傳輸入項時注意:
如何在Servlet中讀取文件上傳數據,並保存到本地硬碟中?
⑵ Java利用HttpURLConnection發送post請求上傳文件
在頁面里實現上傳文件不是什麼難事 寫個form 加上enctype = multipart/form data 在寫個接收的就可以了 沒租褲什麼難的 如果要用 HttpURLConnection來實現文件上傳 還真有點搞頭 : )
先寫個servlet把接收到的 HTTP 信息保存在一個文件中 看一下 form 表單到底封裝了什麼樣的信息
Java代碼
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
//獲取輸入流 是HTTP協議中的實體內容
ServletInputStream in=request getInputStream();
//緩沖區
byte buffer[]=new byte[ ];
FileOutputStream out=new FileOutputStream( d:\test log );
int len=sis read(buffer );
//把流里的信息循環讀入到file log文件中
while( len!= ){
out write(buffer len);
len=in readLine(buffer );
}
out close();
in close();
}
來一個form表單
<form name= upform action= upload do method= POST
enctype= multipart/form data >
參數<input type= text name= username /><br/>
文件 <input type= file name= file /><br/>
文件 <input type= file name= file /><br/>
<input type= submit value= Submit />
<br />
</form>
假如我參數寫的內容是hello word 然後二個文件是二個簡單的txt文件梁譽 上傳後test log里如下
Java代碼
da e c
Content Disposition: form data; name= username
hello word
da e c
Content Disposition: form data; name= file ; filename= D:haha txt
Content Type: text/plain
haha
hahaha
da e c
Content Disposition: form data; name= file ; filename= D:huhu txt
Content Type: text/plain
messi
huhu
da e c
研究下規律發現有如下幾點特徵
第一行是 d b bc 作為分隔符 然後是 回車換行符 這個 d b bc 分隔符瀏覽器是隨機生成的
第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=對應input的name值 filename對應要上傳的文件名(包括路徑在內)
第三行如果是文件就有Content Type: text/plain 這里上傳的是txt文件所以是text/plain 如果上穿的是jpg圖片的話就是image/jpg了 可以自己試試看看
然後就是回弊渣簡車換行符
在下就是文件或參數的內容或值了 如 hello word
最後一行是 da e c 注意最後多了二個 ;
有了這些就可以使用HttpURLConnection來實現上傳文件功能了
Java代碼 public void upload(){
List<String> list = new ArrayList<String>(); //要上傳的文件名 如 d:haha doc 你要實現自己的業務 我這里就是一個空list
try {
String BOUNDARY = d a d c ; // 定義數據分隔線
URL url = new URL( );
HttpURLConnection conn = (HttpURLConnection) url openConnection();
// 發送POST請求必須設置如下兩行
conn setDoOutput(true);
conn setDoInput(true);
conn setUseCaches(false);
conn setRequestMethod( POST );
conn setRequestProperty( connection Keep Alive );
conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );
conn setRequestProperty( Charsert UTF );
conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);
OutputStream out = new DataOutputStream(conn getOutputStream());
byte[] end_data = ( + BOUNDARY + ) getBytes();// 定義最後數據分隔線
int leng = list size();
for(int i= ;i<leng;i++){
String fname = list get(i);
File file = new File(fname);
StringBuilder *** = new StringBuilder();
*** append( );
*** append(BOUNDARY);
*** append( );
*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );
*** append( Content Type:application/octet stream );
byte[] data = *** toString() getBytes();
out write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = ;
byte[] bufferOut = new byte[ ];
while ((bytes = in read(bufferOut)) != ) {
out write(bufferOut bytes);
}
out write( getBytes()); //多個文件時 二個文件之間加入這個
in close();
}
out write(end_data);
out flush();
out close();
// 定義BufferedReader輸入流來讀取URL的響應
BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));
String line = null;
while ((line = reader readLine()) != null) {
System out println(line);
}
} catch (Exception e) {
System out println( 發送POST請求出現異常! + e);
e printStackTrace();
}
lishixin/Article/program/Java/hx/201311/27114
⑶ java 上傳文件 問題
不用 下載相應jar包 引入就可以了 import 你懂得
⑷ java實現文件上傳,代碼盡量簡潔~~~~~·
你說的2種方法都是很簡單的,參考網上的資料都不難做出,用io流做更是基礎中的基礎,我說下smartupload好了,有的人是直接寫在jsp上面,感覺比較亂,我一般都是寫在action裡面,打好jar包和配置後
SmartUpload mySmartUpload = new SmartUpload();
//如果是struts2.0或者webwork 則是mySmartUpload.initialize(ServletActionContext.getServletConfig(),ServletActionContext.getRequest(),ServletActionContext.getResponse());
mySmartUpload.initialize(servlet.getServletConfig(), request,response);
mySmartUpload.setTotalMaxFileSize(500000);
//如果上傳任意文件不設置mySmartUpload.setAllowedFilesList(文件後綴名)就可以了
mySmartUpload.upload();
for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
com.jspsmart.upload.File file = mySmartUpload.getFiles().getFile(i);
if (file.isMissing()) continue;
file.saveAs(保存的地址 + file.getFileName(),
su.SAVE_PHYSICAL);
⑸ java使用ServletFileUpload上傳文件,ServletFileUpload.parseRequest(request)報錯。
操作不允許,/trs/apache-tomcat-7.0.37/yy/kjcg/uploadtmp/upload__bf6b7e9_14520c5a8b9__8000_00000000.tmp不能創建。查查tomcat所屬用戶的/trs/apache-tomcat-7.0.37/yy/kjcg/uploadtmp目錄寫許可權