[精彩] 疑问:文件图片上传、在线发送EMAIL?

[精彩] 疑问:文件图片上传、在线发送EMAIL?,第1张

[精彩] 疑问文件/图片上传、在线发送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;
      }
    }
 
 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/2082213.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-07-22
下一篇 2022-07-22

发表评论

登录后才能评论

评论列表(0条)

保存