[精彩] 疑問:文件/圖片上傳、在線發送EMAIL?
package uploadfile;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;?
import java.io.FileOutputStream;
import java.io.*;
import java.util.Hashtable;
import java.util.*;
public class FileUploadBean {
?? private String savePath=null;???? //
文件上傳
保存的路徑
?? private String contentType="";??? //內容類型
?? private String charEncode=null;?? //字符編碼
?? private String boundary="";?????? //分界線
?? private String fileName=null;?????? //本地文件名字
?? private Hashtable dic=new Hashtable(); //用于保存"元素名--元素值"對??????
?? private int totalSize=0;?????? //上傳文件總大小
?? private String path="";?????? //保存文件的路徑
?? private String newFileName="";???????????? //存入隨機產生的文件名
???
?? ///////////////////////////////////////////////////
?? //設置
文件上傳
保存的路徑
?? public void setSavePath(String s) {
? s=path+s;
????? savePath=s;
? System.out.println("上傳路徑:"+savePath);
?? }
???
?? ///////////////////////////////////////////////////
?? //取
文件上傳
保存的路徑
?? public String getSavePath() {
????? return savePath;
??????
?? }
???
?? ////////////////////////////////////////////////////
?? //設置文件名字,也可以為它命名,暫時先用它原來的名字
?? public void setFileName(String s) {
????? int pos=s.indexOf("\"; filename=\"");
????? if (pos>;0) {
???????? s=s.substring(pos+13,s.length()-3); //去 " 和 crlf
???????? pos=s.lastIndexOf("\\");
???????? if (pos<0)
??????????? pos=s.lastIndexOf("/");
??????????? if (pos<0)
?????????????? fileName=s;
???????? fileName=s.substring(pos+1);??????
????? }
?? }
???
?? ////////////////////////////////////////////////////
?? //取得文件名
?? public String getFileName() {
?????? System.out.println("得到文件名"+newFileName);
?? return newFileName;
?????
?? }
?? ///////////////////////////
?? //以時間為種子數產生新文件名
?? public String getNewFileName() {
?????? int pos=0;???????????????????????? //.的位置
?? long seed=0;?????????????????????? //隨機種子數
?? String ext="";? //存入文件擴展名
?? System.out.println("upload file name:"+fileName);
?? pos=fileName.lastIndexOf(".");
?? ext=fileName.substring(pos);?????? //得到擴展名
?? seed=new Date().getTime();
?? Random rand=new Random(seed);//以時間為種子產生隨機數作為文件名
?? newFileName=Long.toString(Math.abs(rand.nextInt()))+ext;?? //生成文件名
?? System.out.println("new file name:"+newFileName);
?? return newFileName;
?????
?? }
?? //////////////////////////////////////////////////////
?? //設置字符的編碼方式
?? public void setCharEncode(HttpServletRequest req) {
????? charEncode=req.getCharacterEncoding();
?? }
???
???
???
???
?? /////////////////////////////////////////////////
?? //設置得ContentType
?? public void setBoundary(HttpServletRequest req) {
???? //傳遞的參數值類似"multipart/form-data; boundary=---------------------------7d21441a30013c"
???? //傳過來的分界線比實際顯示在上傳數據中的要多兩個"--"
?
???? boundary=req.getContentType();
?//System.out.println("boundary"+boundary);
???????? int pos=boundary.indexOf("boundary=");
???????? //加上這兩個"--"
???????? boundary="--"+boundary.substring(pos+9);?????
?????
?
?? }
???
?? ////////////////////////////////////////////////////
?? //取得ContentType
?? public String getBoundary(){
????? //返回值類似"-----------------------------7d21441a30013c"?
????? return boundary;?
?? }
???
???
?? /////////////////////////////////////////////
?? //設置ContentType
?? public void setContentType(String s) {
????? int pos =s.indexOf(": ");
????? if (pos!=-1)
???????? contentType=s.substring(pos+2);
?? }
???
?? ////////////////////////////////////////////
?? //取得ContentType
?? public String getContentType() {
????? return contentType;
?? }
???
?? /////////////////////////////////////////////
?? //初始化
?? public void init(HttpServletRequest req) {
????? setCharEncode(req);
????? setBoundary(req);
?????
?? }
???
???
?? ////////////////////////////////////////////////////
?? //取哈希表中的數據
?? public String getFieldValue(String s) {
????? String temp="";
?? if(dic.containsKey(s))?????? //判斷表中是否存在s鍵,不判斷則返回nullpointerException
? {
? temp=(String)dic.get(s);
????? temp=temp.trim();???
? }else
? temp="";
?? return temp;
?? }
???
???
???
?? ////////////////////////////////////////////////
?? ////用指定的編碼方式生成字符串
?? public String newLine(byte oneLine[],int sp,int i,String charEncode)
????????? throws java.io.UnsupportedEncodingException? {
????? sp=0;? // start position
????? String lineStr=null;
????? if (charEncode!=null) {??????
????????? return lineStr=new String(oneLine,sp,i,charEncode); //用指定的編碼方式生成字符串
????? }
????? else {
???????? return lineStr=new String(oneLine,sp,i);
????? }
?? }
???
?? ///////////////////////////////////////////////
?? //得到上傳文件的大小
?? public int getTotalSize() {
???? return totalSize/1000;
?? }
?? ///////////////////////////////////////
?? //刪除指定路徑的文件
?? public boolean delFiles(String fn)? //fn為要刪除的文件名,不包括路徑
?? {
?? try
?? {
?? File file=new File(savePath+fn);?
?? System.out.println(savePath+fn);
?? if(file.exists())
? {
???? file.delete();
???? System.out.println(file.getPath()+"delete file successfully!");
?return true;
?????? }else
?? {
?System.out.println("the file is not existed!");
?return true;
??? }
?? }catch(Exception e)
?? {
?? System.out.println(e.toString());
?? return false;
?? }
?? }
???
?? ////////////////////////////////////////////////
?? //文件列表
?? public String[] listFiles(String fp)
?? {
??? String[] lf=null;
?? try{
????? savePath=path+fp;
????? File file=new File(savePath);
????? lf=file.list(new DirFilter());
? for(int i=0;i<lf.length;i++)
? System.out.println(lf);
?? }catch(Exception e){ e.printStackTrace();}
?? return lf;
?? }
?? /////////////////////////////////////////////////
?? //開始上傳文件
?? public boolean doUpload(HttpServletRequest req)?
????????? throws java.io.IOException {
?????
???? String fieldValue="";? //表單元素值
???? String fieldName="";?? //表單元名稱
???? int pos=-1;??????????? //臨時變量,用于記錄位置
???? int pos2=-1;?????????? //臨時變量,用于記錄位置
???? String lineStr=null;??????????? //用oneLine[]生成的每行字符串
???? byte oneLine[] =new byte[4096]; //用于每次讀取的數據
???? FileOutputStream fos=null;????? //文件輸出流
???? init(req); //初始化
???? ServletInputStream sis=req.getInputStream();
???? int i=sis.readLine(oneLine,0,oneLine.length); //返回實際讀取的字符數,并把數據寫到oneLine中
???? while (i!=-1) {
????????? lineStr=newLine(oneLine,0,i,charEncode); //生成字符串
????????? if (lineStr.indexOf(getBoundary()+"--")>;=0)
????????????? break;
??
????????? if (lineStr.startsWith("Content-Disposition: form-data; name=\"")) {
???????????? //分離數據,因為表單元素也一并上傳,還有其它數據,對我們有用的只是
???????????? //文件的內容,表單元素及表單元素對應的值
???????????? if (lineStr.indexOf("\"; filename=\"")>;=0) { //是文件輸入域
??????????????? //設置文件名
??????????????? setFileName(lineStr);
?????????????? if (!fileName.equals("")) { //如果文件名為空則跳過
????????????????
?????????????????? //提取表單元素名稱及表單元素對應的值
?????????????????? pos=lineStr.indexOf("name=\"");
?????????????????? pos2=lineStr.indexOf("\"; filename=\"");
?????????????????? //表單元素名字
?????????????????? fieldName=lineStr.substring(pos+6,pos2);
?????????????????? //表單元素值
?????????????????? fieldValue=lineStr.substring(pos2+13,lineStr.length()-3);
?????????????????? //加入哈希表中
?????????????????? dic.put(fieldName,fieldValue);
?????????????????? sis.readLine(oneLine,0,oneLine.length); //讀取的數據類似"Content-Type: text/plain"
?????????????????? sis.readLine(oneLine,0,oneLine.length); //空行
?????????????????? //建立文件輸出
?????????????????? fos=new FileOutputStream(new File(getSavePath(),getNewFileName()));
?????????????????? //開始讀上傳文件數據
?????????????????? i=sis.readLine(oneLine,0,oneLine.length);
?????????????????? while(i!=-1) {
????????????????????? totalSize=i+totalSize;
????????????????????? lineStr=newLine(oneLine,0,i,charEncode);
????????????????????? if (lineStr.indexOf(getBoundary())>;=0)
???????????????????????? break; //表明這個文件區的數據讀取完畢
????????????????????? fos.write(oneLine,0,i);
????????????????????? i=sis.readLine(oneLine,0,oneLine.length);
?????????????????? }//end while
?????????????????? fos.close();
??????????????? }//end if (!getFileName().equals(""))
???????????? }
???????????? else { //非文件輸入域
??????????????? pos=lineStr.indexOf("name=\"");
??????????????? //表單元素名字
??????????????? fieldName=lineStr.substring(pos+6,lineStr.length()-3);
??????????????? //讀空行
??????????????? sis.readLine(oneLine,0,oneLine.length);
??????????????? //這行含有元素值,如里元素值為空,則這行也是空行,也要讀的
??????????????? String temp="";
i=sis.readLine(oneLine,0,oneLine.length);
while(i!=-1)
{
?? temp=newLine(oneLine,0,i,charEncode);
?? if (temp.indexOf(getBoundary())>;=0)
???????????????????????? break;?
?????????????????? fieldValue=fieldValue+temp;
?? i=sis.readLine(oneLine,0,oneLine.length);
}??
??????????????? //加入哈希表中
??????????????? dic.put(fieldName,fieldValue);
fieldValue="";
???????????? }?????????????
????????? }
????????? i=sis.readLine(oneLine,0,oneLine.length);
???? }//end while
?????
???? sis.close();
?
???? return true;
?? } //end doUpload
???
???
//////////////////////////
//清空Hashtable
?? public void clearDic() {
? dic.clear();
? if (dic.isEmpty()) {
? System.out.println("empty");
? }
? else {
????? System.out.println("not empty");
? }
??
?? }
//////////////////////////////////
//測試用的主函數
? public static void main(String args[])
?? {
?? String[] fileList=null;
?? try{
????? FileUploadBean fub=new FileUploadBean();
????? fileList=fub.listFiles("/avatars/");
?? for(int i=0;i<fileList.length;i++)
?? System.out.println(fileList);
???
?? }catch(Exception e){ e.printStackTrace();}
?? }
????
}
///////////////////////////////////
////文件目錄過濾內部類
?? class DirFilter implements FilenameFilter {
??
????? public boolean accept(File dir, String name) {?? //dir為目錄名,name 為包含路徑的文件名
??
???????? File f = new File(dir,name);?? //生成文件對象
???? if(f.isDirectory())
???? return false;
???????? return true;
????? }
??? }
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
