⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileupload.java

📁 J2EE+jsp音乐网站,提供登录
💻 JAVA
字号:
package com.music;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FileUpload{
    private String saveDir = "."; //要保存文件的路径
    private String contentType = ""; //文档类型
    private String charset = ""; //字符集
    private ArrayList tmpFileName = new ArrayList(); //临时存放文件名的数据结构
    private Hashtable parameter = new Hashtable(); //存放参数名和值的数据结构
    private ServletContext context; //程序上下文,用于初始化
    private HttpServletRequest request; //用于传入请求对象的实例
    private String boundary = ""; //内存数据的分隔符
    private int len = 0; //每次从内在中实际读到的字节长度
    private String queryString;
    private int count; //上载的文件总数
    private String[] fileName; //上载的文件名数组
    private long maxFileSize = 1024 * 1024 * 10; //最大文件上载字节;
    private String tagFileName = "";
    //数据库相关信息
	private Connection conn;
	private Statement StMent;
    private PreparedStatement pst;
    private String DataSoure="";
    private String sqluser="";
    private String sqlpwd="";
    
    //音乐文件名称
    private String MusicName="";
    
    public final void init(HttpServletRequest request) throws ServletException {
        this.request = request;
        boundary = request.getContentType().substring(30); //得到内存中数据分界符
        queryString = request.getQueryString();
    }

    /**
     * 用于得到指定字段的参数值,重写request.getParameter(String s)
     * @param s 参数名
     * @return 对应s的参数值
     */
    public String getParameter(String s) {
        if (parameter.isEmpty()) {
            return null;
        }
        return (String) parameter.get(s);
    }

    /**
     * 用于得到指定同名字段的参数数组,重写request.getParameterValues(String s)
     * @param s 参数名
     * @return 对应s的参数值列表
     */
    public String[] getParameterValues(String s) { 
        ArrayList al = new ArrayList();
        if (parameter.isEmpty()) {
            return null;
        }
        Enumeration e = parameter.keys();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            if (-1 != key.indexOf(s + "||||||||||") || key.equals(s)) {
                al.add(parameter.get(key));
            }
        }
        if (al.size() == 0) {
            return null;
        }
        String[] value = new String[al.size()];
        for (int i = 0; i < value.length; i++) {
            value[i] = (String) al.get(i);
        }
        return value;
    }

    
    public String getQueryString() {
        return queryString;
    }

    public int getCount() {
        return count;
    }

    public String[] getFileName() {
        return fileName;
    }

    public void setMaxFileSize(long size) {
        maxFileSize = size;
    }

    public void setTagFileName(String filename) {
        tagFileName = filename;
    }

    /**
     * 设置上载文件要保存的路径
     * @param saveDir 上传文件保存路径
     */
    public void setSaveDir(String saveDir) {        
        this.saveDir = saveDir;
        File testdir = new File(saveDir); //为了保证目录存在,如果没有则新建该目录
        if (!testdir.exists()) {
            testdir.mkdirs();
        }
    }

    /**
     * 设置字符集
     * @param charset 字符集名称
     */
    public void setCharset(String charset) {        
        this.charset = charset;
    }

    /**
     * 用户调用的上载方法
     * @return 用户调用的上载方法
     * @throws ServletException
     * @throws IOException
     */
    public boolean uploadFile() throws ServletException, IOException {        
        setCharset(request.getCharacterEncoding());
        return uploadFile(request.getInputStream());
    }

    private boolean uploadFile(ServletInputStream servletinputstream) throws ServletException, IOException {
        //取得央存数据的主方法
        String line = null;
        byte[] buffer = new byte[256];
        while ((line = readLine(buffer, servletinputstream, charset)) != null) {
            if (line.startsWith("Content-Disposition: form-data;")) {
                int i = line.indexOf("filename=");
                if (i >= 0) { //如果一段分界符内的描述中有filename=,说明是文件的编码内容
                    String fName = getFileName(line);
                    if (fName.equals("")) {
                        continue;
                    }
                    if (count == 0 && tagFileName.length() != 0) {
                        String ext = fName.substring((fName.lastIndexOf(".") + 1));
                        fName = tagFileName + "." + ext;
                    }
                    tmpFileName.add(fName);
                    count++;
                    while ((line = readLine(buffer, servletinputstream, charset)) != null) {
                        if (line.length() <= 2) {
                            break;
                        }
                    }
                    File f = new File(saveDir, fName);
                    FileOutputStream dos = new FileOutputStream(f);
                    long size = 0l;
                    while ((line = readLine(buffer, servletinputstream, null)) != null) {
                        if (line.indexOf(boundary) != -1) {
                            break;
                        }
                        size += len;
                        if (size > maxFileSize) {
                            throw new IOException("文件超过" + maxFileSize + "字节!");
                        }
                        dos.write(buffer, 0, len);
                    }
                    dos.close();
                } else { //否则是字段编码的内容
                    String key = getKey(line);
                    String value = "";
                    while ((line = readLine(buffer, servletinputstream, charset)) != null) {
                        if (line.length() <= 2) {
                            break;
                        }
                    }
                    while ((line = readLine(buffer, servletinputstream, charset)) != null) {
                        if (line.indexOf(boundary) != -1) {
                            break;
                        }
                        value += line;
                    }
                    put(key, value.trim(), parameter);
                }
            }
        }
        if (queryString != null) {
            String[] each = split(queryString, "&");
            for (int k = 0; k < each.length; k++) {
                String[] nv = split(each[k], "=");
                if (nv.length == 2) {
                    put(nv[0], nv[1], parameter);
                }
            }
        }
        fileName = new String[tmpFileName.size()];
        for (int k = 0; k < fileName.length; k++) {
            fileName[k] = (String) tmpFileName.get(k); //把ArrayList中临时文件名倒入数据中供用户调用
        }
        if (fileName.length == 0) {
            return false; //如果fileName数据为空说明没有上载任何文件
        }
        return true;
    }
    
   public boolean UpFileToDb() throws ServletException, IOException {        
        setCharset(request.getCharacterEncoding());
        return UpFileToDb(request.getInputStream());
    }
    //上载文件到数据库
   private boolean UpFileToDb(ServletInputStream servletinputstream)
   throws ServletException, IOException
    {
	   //OutputStream out=new FileOutputStream("c:\\1.doc");
       //取得央存数据的主方法
       String line = null;
       //OutputStream out=null;
      // OutputStream out=new FileOutputStream("c:\\1.doc"); 
      // InputStream in=null;
       byte[] buffer = new byte[256];
       while ((line = readLine(buffer, servletinputstream, charset)) != null) {
    	   //if(line.startsWith("MusicName"));	
           if (line.startsWith("Content-Disposition: form-data;")) {
               int i = line.indexOf("filename=");
               if (i >= 0) { //如果一段分界符内的描述中有filename=,说明是文件的编码内容
                   String fName = getFileName(line);
                   if (fName.equals("")) {
                       return false;
                   }
                   while ((line = readLine(buffer, servletinputstream, charset)) != null) {
                       if (line.length() <= 2) {
                           break;
                       }
                   }
                   File f = new File(saveDir, fName);
                   FileOutputStream dos = new FileOutputStream(f);
                   long size = 0l;
                   while ((line = readLine(buffer, servletinputstream, null)) != null) {
                       if (line.indexOf(boundary) != -1) {
                           break;
                       }
                       size += len;
                       //dos.write(buffer, 0, len);
                       dos.write(buffer, 0, len);
                   }
                   dos.close();
                   InputStream in=new FileInputStream(f); 
            	   try
            	   {
            	    	  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            	          conn = DriverManager.getConnection(this.DataSoure,this.sqluser,this.sqlpwd);
            	          System.out.print("dddddddddd");
            	          System.out.print(MusicName);
            	          String InsertStr = "insert into MusicInfor(MusicName,MusicData,SongsterID) values(?,?,NULL)";
            	          pst = conn.prepareStatement(InsertStr); 
            	          fName=fName.replace(" ","");
            	          pst.setString(1,fName.substring(0,fName.length()-4));
            	          //pst.setString(1,MusicName);
            	          pst.setBinaryStream(2,in,in.available());
            	          pst.executeUpdate(); 
            	          pst.close();
            	          conn.close(); 
            	   }
            	   catch(Exception e)
            	   {
            		    System.out.println("插入数据出错\n" + e.getMessage()); 
            		    f.delete();
            		    return false;
            	   }
            	   in.close();
            	   f.delete();
               } else { //否则是字段编码的内容
                   String key = getKey(line);
                   String value = "";
                   while ((line = readLine(buffer, servletinputstream, charset)) != null) {
                       if (line.length() <= 2) {
                           break;
                       }
                   }
                   while ((line = readLine(buffer, servletinputstream, charset)) != null) {
                       if (line.indexOf(boundary) != -1) {
                           break;
                       }
                       value += line;
                   }
                   put(key, value.trim(), parameter);
               }
           }
       }
       if (queryString != null) {
           String[] each = split(queryString, "&");
           for (int k = 0; k < each.length; k++) {
               String[] nv = split(each[k], "=");
               if (nv.length == 2) {
                   put(nv[0], nv[1], parameter);
               }
           }
       }
	    return true;
    }
    //设置数据源名称
   public boolean SetConnectString(String DataSoure,String sqluser,String sqlpwd)
   {
	   this.DataSoure=DataSoure;
	   this.sqluser=sqluser;
	   this.sqlpwd=sqlpwd;
	   return true;
   }
   public void GetMusicName(String szMusciName)
   {
	   this.MusicName=szMusciName;
	   System.out.print(szMusciName);
	   System.out.print(this.MusicName);
   }
    /**
     * 从描述字符串中分离出字段名
     * @param line
     * @return
     */
    private String getKey(String line) { 
        if (line == null) {
            return "";
        }
        int i = line.indexOf("name=");
        line = line.substring(i + 5).trim();
        return line.substring(1, line.length() - 1);
    }

    public static String[] split(String strOb, String mark) {
        if (strOb == null) {
            return null;
        }
        StringTokenizer st = new StringTokenizer(strOb, mark);
        ArrayList tmp = new ArrayList();
        while (st.hasMoreTokens()) {
            tmp.add(st.nextToken());
        }
        String[] strArr = new String[tmp.size()];
        for (int i = 0; i < tmp.size(); i++) {
            strArr[i] = (String) tmp.get(i);
        }
        return strArr;
    }

    /**
     * 从描述字符串中分离出文件名
     * @param line
     * @return
     */
    private String getFileName(String line) {
       
        if (line == null) {
            return "";
        }
        int i = line.indexOf("filename=");
        line = line.substring(i + 9).trim();
        i = line.lastIndexOf("\\");
        if (i < 0 || i >= line.length() - 1) {
            i = line.lastIndexOf("/");
            if (line.equals("\"\"")) {
                return "";
            }
            if (i < 0 || i >= line.length() - 1) {
                return line;
            }
        }
        return line.substring(i + 1, line.length() - 1);
    }

    /**
     * 
     * @param Linebyte
     * @param servletinputstream
     * @param charset
     * @return
     */
    private String readLine(byte[] Linebyte, ServletInputStream servletinputstream, String charset) {
        try {
            len = servletinputstream.readLine(Linebyte, 0, Linebyte.length);
            if (len == -1) {
                return null;
            }
            if (charset == null) {
                return new String(Linebyte, 0, len);
            } else {
                return new String(Linebyte, 0, len, charset);
            }
        } catch (Exception _ex) {
            return null;
        }
    }

    private void put(String key, String value, Hashtable ht) {
        if (!ht.containsKey(key)) {
            ht.put(key, value);
        } else { //如果已经有了同名的KEY,就要把当前的key更名,同时要注意不能构成和KEY同名
            try {
                Thread.sleep(1); //为了不在同一ms中产生两个相同的key
            } catch (Exception e) {
            }
            key += "||||||||||" + System.currentTimeMillis();
            ht.put(key, value);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -