java 文件上传 servlet_java文件上传-原始的Servlet方式
前言:
干了這幾個項目,也做過幾次文件上傳下載,要么是copy項目以前的代碼,要么是百度的,雖然做出來了,但學習一下原理弄透徹還是很有必要的。剛出去轉了一圈看周圍有沒有租房的,在北京出去找房子是心里感覺最不爽的時候,沒有歸屬感,房租還不便宜,RT,不能好高騖遠,還是腳踏實地一點一點學技術吧,終將有一日,工資會漲的。
java文件上傳
傳統的文件上傳,不用jquery插件的話,就是用form表單提交,項目里用過uploadify,可以異步上傳文件,原理我也沒研究。現在說傳統的form表單上傳文件。
文件上傳核心:
用 來聲明一個文件域。樣式如 ?文件:_____ .
必須使用post方式提交表單。
必須設置表單的類型為multipart/form-data.是設置這個表單傳遞的不是key=value值。傳遞的是字節碼.
新建web項目:
jsp form表單:enctype(編碼類型)的默認值就是?application/x-www-form-urlencoded
瀏覽器查看 http報文:
主要參數:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 ? ?接收服務器返回的類型,*/*表示所有。
Referer:http://localhost:8888/upload/ ? ?來自哪個網站
Accept-Language:zh-CN,zh;q=0.8 :請求回應中首選的語言為簡體中文
Accept-Encoding:gzip, deflate, br支持的壓縮格式
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 ??用戶瀏覽器類型
Host:localhost:8888 主機地址
Connection:keep-alive?報文發送完畢后仍然保持連接
Cache-Control:max-age=0 ?緩存
Content-Length:41 41字節
對文件上傳來說,重要的參數是:
Content-Type:application/x-www-form-urlencoded
這個參數只有post請求才有,默認就是application/x-www-from-urlencoded ,Content-type表示正文類型,get方式沒有正文,因為參數在url里。
在Servlet里可以用request對象取到Content-type:request.getHeader("Content-type"); 默認的值為 application/x-www-form-urlencoded,
如果是get請求,則request.getHeader("Content-type");為null。
下圖是get請求時的http頭信息,參數再url傳遞,沒有Content-type
文件上傳,必須設置enctype="multipart/form-data"
from表單:
上傳一個word:
此時的http消息的Content-Type:
其中的 boundary=----WebKitFormBoundary44gVxAkoSg3tk3oR 指的是文件上傳的分隔符。在請求正文里體現。
看請求的正文:
-----xxxxxxxxxx 標識文件開始,最后一行的 --------xxxxxxxxxxxx--(分隔符末尾多了2個--),標識文件結束。第一個input 是text類型,第二個是二進制,content-type 是application/octet-stream 表示 二進制流。如果選擇的是圖片,Content-Type: image/jpeg,文本則,Content-Type: text/plain。
二進制流的接收:
當表單類型是post類型,切enctype="multipart/form-data",則所有的數據都是以二進制流的形式向服務器上傳,所以request.getParameter("xxx") 永遠為null,只能通過req.getInputStream(); 獲取正文。
上傳一個txt:
Servlet:
packagecom.lhy.upload;importjava.io.BufferedReader;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;/***
*@authorAdministrator
**/@WebServlet(name="UploadServlet",urlPatterns="/UploadServlet")public class UploadServlet extendsHttpServlet{
@Overrideprotected voiddoGet(HttpServletRequest req, HttpServletResponse resp)throwsServletException, IOException {//this.doPost(req, resp);
}
@Overrideprotected voiddoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletException, IOException {
req.setCharacterEncoding("UTF-8");
String contentType= req.getHeader("Content-type");
System.out.println("contentType: "+contentType);
String name= req.getParameter("name");
System.out.println(name);//null
InputStream is=req.getInputStream();//------WebKitFormBoundaryG0ULv7eVfQ1K2PBA//Content-Disposition: form-data; name="image"; filename="靜夜思.txt"//Content-Type: text/plain//
//
//------WebKitFormBoundaryG0ULv7eVfQ1K2PBA--
BufferedReader br = new BufferedReader(newInputStreamReader(is));
String firstLine= br.readLine();//第一行,分隔符
String fileName =br.readLine();//Content-Disposition: form-data; name="image"; filename="jingyesi.txt"
fileName = fileName.substring(fileName.lastIndexOf("=")+2,fileName.length()-1);
br.readLine();
br.readLine();
String data= null;//獲取當前項目的運行路徑
String path = getServletContext().getRealPath("/up");
PrintWriter pw= new PrintWriter(path+"/"+fileName);while((data = br.readLine()) != null){if(data.equals(firstLine+"--")){break ; //讀到了文件尾
}
pw.println(data);
}
pw.flush();
pw.close();
is.close();/*FileOutputStream fos = new FileOutputStream(path+"/"+"b.doc");
// byte[] b = new byte[1024];
int len = 0;
while((len = is.read()) != -1){
fos.write(len);
}
fos.flush();
fos.close();
is.close();*/}
}
項目里:
例子只是讀取了txt,其他的二進制需要使用inputStream讀取。
我讀取了圖片寫到項目里,打不開,大小比原始圖片會小一點,不知為何
歡迎關注個人公眾號一起交流學習:
總結
以上是生活随笔為你收集整理的java 文件上传 servlet_java文件上传-原始的Servlet方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: selenium java测试_java
- 下一篇: java 什么是耦合_什么是耦合、解耦