文件上傳在HTML中是以
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="upload1"/><br />
<input type="submit" value="上傳"/>
</form>
形式出現(xiàn)的。
文件上傳有兩種選擇:
(1)SmartUpload:以jar包形式出現(xiàn),需要把他添加到classpath或tomcat的lib文件夾下。
(2)FileUpload:以jar包形式出現(xiàn),需要把他添加到classpath或tomcat的lib文件夾下。注意:此包與common-io包是相互依賴(lài)的,因此需要同時(shí)存放。
對(duì)于SmartUpload,使用較方便,但是官方已經(jīng)不能下載。
SmartUpload smart = new SmartUpload();
smart.initialize(pageContext);
smart.upload(); //準(zhǔn)備上傳
smart.save("file");
實(shí)現(xiàn)的功能是將上傳到的文件保存在/file文件夾下,并以同名進(jìn)行保存。
文件上傳規(guī)定:表單必須有enctype="multipart/form-data"這個(gè)屬性;因此表單是以二進(jìn)制數(shù)據(jù)發(fā)送的,比如表單中有一個(gè)text,2個(gè)上傳控件,發(fā)送數(shù)據(jù)時(shí)是一起以二進(jìn)制發(fā)送的。
因?yàn)橛辛宋募蟼骺丶螅韱蔚钠渌丶鬟f數(shù)據(jù)不能通過(guò)普通的request.getParameter(),而需要smart.getRequest().getParameter();
String ext = smart.getFiles().getFile(0).getFileExt();// 獲得文件后綴
smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/")+filename+"."+ext); // 另存為自定義文件名
filename就是文件自定義名稱(chēng),ext就是文件擴(kuò)展名。
for(int i=0;i<smart.getFiles().getCount();i++){
String ext = smart.getFiles().getFile( i ).getFileExt();
smart.getFiles().getFile( i ).saveAs(this.getServletContext().getRealPath("/")+filename+"."+ext);
}即可。
從以上看出,SmartUpload的代碼量不會(huì)特別多,比較方便。
FileUpload是apache的commons項(xiàng)目的子項(xiàng)目,需要下載jar包,注意:還要把commons-io.jar也下下來(lái),因?yàn)檫@兩個(gè)包是相互關(guān)聯(lián)的。
一般需要導(dǎo)入:
(1)org.apache.commons.fileupload.*;
(2)org.apache.commons.fileupload.servlet.*;
(3)org.apache.commons.fileupload.disk.*;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(1024*1024); //設(shè)置上傳文件的最大容量
List<FileItem>items = upload.parseRequest(request); //取得表單全部數(shù)據(jù)
含有文件上傳控件的表單是不能區(qū)分一般控件和上傳控件的,都作為FileItem;
通過(guò)item.isFormField()能夠判斷,如果返回true,則表示一般控件數(shù)據(jù)。
(1)如果是一般控件,則item.getString()即可。
item.getFieldName()返回域名稱(chēng)。
(2)如果是文件上傳控件,則包含一些方法
item.getName(); 取得上傳文件的名稱(chēng)
item.getContentType(); 取得上傳文件的mime類(lèi)型
long item.getSize();取得上傳文件的大小
item.getInputStream();取得上傳文件的輸入流
在SmartUpload中,只需要save函數(shù)即可,但是在FileUpload中,需要IO流。
InputStream input = item.getInputStream();
FileOutputStream output = new FileOutputStream("file.txt");
byte[] buf = new byte[1024];
int length = 0;
while((length=input.read(buf))!=-1){
output.write(buf,0,length);
}
input.close();
output.close();
即可。
String ext = item.getName().split("\\.")[1];
對(duì)于打文件,需要設(shè)置臨時(shí)文件夾,形式:
factory.setRepository("filename");
聯(lián)系客服