上傳文件組件說明
上傳組件設計思想:
這裏的自制上傳組件用的是HttpServletRequest 方法上傳的
,
首先我們通過 HttpServletRequest 方法獲取到 request所獲取
到的http傳過來的流,然後將流讀入到一個臨時文件內.然後我們用一個方法來解析這個文件.因爲通過http傳過來的流生成的臨時
文件的結構如下:
-----------------------------7d33a816d302b6
Content-Disposition: form-data; name="userfile1"; filename="E:/s"
Content-Type: application/octet-stream
a
bb
XXX
ccc
-----------------------------7d33a816d302b6
Content-Disposition: form-data; name="text1"
foo
-----------------------------7d33a816d302b6
Content-Disposition: form-data; name="password1"
bar
-----------------------------7d33a816d302b6--
然後我們只需要解析臨時文件,就能提取出上傳文件內容和上傳控件內容.在解析上傳文件時,一併將文件類型,文件大小獲取到.並
且我們可以根據這樣的方法限制上傳文件大小和類型
.
我們將獲取到的上傳控件名和上傳控件值存入到hashtable(K,V)中.
將獲取到的上傳文件流的信息(文件名,文件大小,文件類型…)存入到Vector中.然後將存入到Vector相應的索引和控件名存入到
Hashtable中.
這樣我們就可以將上傳流和控件對應的值獲取到.然後在重載getParameter()方法,並且 一併重載request的其他方法.這樣 一個
完整的上傳文件空間就做成了.
本上傳組件使用方法
方法摘要
方法名
|
參數類型 |
返回值 |
說明 |
SetSize(int number)
|
Int類型 |
Void |
設置上傳文件的大小,若不設置,則只能上傳10M文件,若
設爲-1,則上傳文件大小不控制
|
setSuffix(String suffix)
|
String 類型 |
Void |
設置上傳文件類型若不設置,則可以上傳所有文件.[例如:
.gif.png]
|
getFieldValue(String ctlname)
|
String 類型 |
String |
獲取相應控件的值 比如:若String username =
ulb.getFieldValue("username"); 則爲獲取控件名爲
username中的值.
|
getFileValue(String cltname)
|
String類型 |
Byte[] |
獲取上傳組件文件的流以便存入到數據庫中 例如:byte[]
filename1 = ulb.getFileValue(“filename1”);則爲 獲取上傳
控件名爲filename1中的上傳文件流
|
getFilename(String ctlname)
|
String 類型 |
String |
獲取上傳文件的文件名 比如: String filename2 =
ulb.getFilename(“filename1”); 則爲獲取上傳控件名爲
filename1中的上傳文件的文件名
|
getContentType(String ctlname)
|
String 類型 |
String |
獲取上傳文件類型 比如: String filetype2 =
ulb.getContentType(“filename1”); 則爲獲取上傳控件名爲
filename1中的上傳文件的類型
|
getFileLength(String ctlname)
|
String 類型 |
String |
獲取上傳文件的大小 比如: String filelength2 =
ulb.getFileLength(“filename1”); 則爲 獲取上傳空間名爲
filename1中的上傳文件的大小
|
以下附上源碼:
- //upload javabean
- package myupload;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.util.Hashtable;
- import java.util.Vector;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletInputStream;
- import javax.servlet.http.Cookie;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
- public class UpLoadBean {
- private HttpServletRequest request = null;
- public UpLoadBean(HttpServletRequest request) {
- this.request = request;
- }
- //方法重載
- public Object getAttribute(String name) {
- return request.getAttribute(name);
- }
- public java.util.Enumeration getAttributeNames() {
- return request.getAttributeNames();
- }
- public java.lang.String getCharacterEncoding() {
- return request.getCharacterEncoding();
- }
- public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException {
- request.setCharacterEncoding(env);
- }
- public int getContentLength() {
- return request.getContentLength();
- }
- public int getLocalPort() {
- return request.getLocalPort();
- }
- public String getLocalAddr() {
- return request.getLocalAddr();
- }
- public String getLocalName() {
- return request.getLocalName();
- }
- public int getRemotePort() {
- return request.getRemotePort();
- }
- public java.lang.String getContentType() {
- return request.getContentType();
- }
- public ServletInputStream getInputStream() throws java.io.IOException {
- return request.getInputStream();
- }
- public java.util.Map getParameterMap() {
- return request.getParameterMap();
- }
- public java.lang.String getProtocol() {
- return request.getProtocol();
- }
- public java.lang.String getScheme() {
- return request.getScheme();
- }
- public java.lang.String getServerName() {
- return request.getServerName();
- }
- public int getServerPort() {
- return request.getServerPort();
- }
- public java.io.BufferedReader getReader() throws java.io.IOException {
- return request.getReader();
- }
- public java.lang.String getRemoteAddr() {
- return request.getRemoteAddr();
- }
- public java.lang.String getRemoteHost() {
- return request.getRemoteHost();
- }
- public void setAttribute(java.lang.String name, Object o) {
- request.setAttribute(name, o);
- }
- public void removeAttribute(java.lang.String name) {
- request.removeAttribute(name);
- }
- public java.util.Locale getLocale() {
- return request.getLocale();
- }
- public java.util.Enumeration getLocales() {
- return request.getLocales();
- }
- public boolean isSecure() {
- return request.isSecure();
- }
- public RequestDispatcher getRequestDispatcher(String path) {
- return request.getRequestDispatcher(path);
- }
- public java.lang.String getRealPath(String path) {
- return request.getRealPath(path);
- }
- public java.lang.String getAuthType() {
- return request.getAuthType();
- }
- public Cookie[] getCookies() {
- return request.getCookies();
- }
- public long getDateHeader(java.lang.String name) {
- return request.getDateHeader(name);
- }
- public java.lang.String getHeader(java.lang.String name) {
- return request.getHeader(name);
- }
- public java.util.Enumeration getHeaders(java.lang.String name) {
- return request.getHeaders(name);
- }
- public java.util.Enumeration getHeaderNames() {
- return request.getHeaderNames();
- }
- public int getIntHeader(java.lang.String name) {
- return request.getIntHeader(name);
- }
- public java.lang.String getPathInfo() {
- return request.getPathInfo();
- }
- public java.lang.String getPathTranslated() {
- return request.getPathTranslated();
- }
- public java.lang.String getContextPath() {
- return request.getContextPath();
- }
- public java.lang.String getQueryString() {
- return request.getQueryString();
- }
- public java.lang.String getRemoteUser() {
- return request.getRemoteUser();
- }
- public boolean isUserInRole(java.lang.String role) {
- return request.isUserInRole(role);
- }
- public java.security.Principal getUserPrincipal() {
- return request.getUserPrincipal();
- }
- public java.lang.String getRequestedSessionId() {
- return request.getRequestedSessionId();
- }
- public java.lang.String getRequestURI() {
- return request.getRequestURI();
- }
- public java.lang.StringBuffer getRequestURL() {
- return request.getRequestURL();
- }
- public java.lang.String getServletPath() {
- return request.getServletPath();
- }
- public HttpSession getSession() {
- return request.getSession();
- }
- public HttpSession getSession(boolean create) {
- return request.getSession(create);
- }
- public boolean isRequestedSessionIdValid() {
- return request.isRequestedSessionIdValid();
- }
- public boolean isRequestedSessionIdFromCookie() {
- return request.isRequestedSessionIdFromCookie();
- }
- public boolean isRequestedSessionIdFromURL() {
- return request.isRequestedSessionIdFromURL();
- }
- public boolean isRequestedSessionIdFromUrl() {
- return request.isRequestedSessionIdFromUrl();
- }
- //重載結束
- //實例化一個tool
- UpLoadTools ultool = new UpLoadTools();
- private String[] sourceFile = new String[255]; //源文件名
- private String[] suffix = new String[255]; //文件後綴名
- private String canSuffix = ".gif.jpg.jpeg.png"; //可上傳的文件後綴名
- private byte[] files = null; //上傳文件數組
- private ServletInputStream inputStream = null; //輸入流
- private int streamLenth = 0; //輸入流長度
- private FileOutputStream tmpfileStream = null; //臨時文件
- private RandomAccessFile randomFile = null; //以隨機讀寫方式打開http臨時流文件
- private String[] description = new String[255]; //描述狀態
- private long size = 1024 * 1024 * 300; //限制大小 若爲-1則不限制
- // 保存名字/對象對應關係
- private Hashtable fields = new Hashtable(); //hashtable
- // 保存所有名字
- private Vector names = new Vector(); //vector
- //上傳文件限制
- public void setSuffix(String canSuffix) {
- this.canSuffix = canSuffix;
- }
- //上傳文件大小限制
- public void setSize(long maxSize) {
- this.size = maxSize;
- System.out.println("新配置" + size + " || 傳過來的參數:" + maxSize);
- }
- //上傳文件主方法
- public void getSourceFile() throws IOException {
- inputStream = request.getInputStream();
- //System.out.println(inputStream + "<br />");
- //==============將上傳文件存入臨時文件=======================
- String tmpfileName = null;
- streamLenth = request.getContentLength();
- tmpfileName = "c://temp//" + request.getSession().getId();
- tmpfileStream = new FileOutputStream(tmpfileName);
- //獲取上傳內容,並將其保存在臨時文件中。
- int bytesRead = 0, totalBytes = 0;
- byte[] cnt;
- while (totalBytes < streamLenth) {
- cnt = new byte[256];
- bytesRead =
- inputStream.read(cnt, 0, 256); //中的方法在此字節輸入流中從給定的偏移量開始將各字節讀取到指定的 byte 數組中
- totalBytes += bytesRead;
- tmpfileStream.write(cnt);
- }
- tmpfileStream.close();
- inputStream.close();
- //現已將Http協議上傳的內容全部寫入了臨時文件。以下的代碼便可在服務器上對上傳的內容進行解釋
- //======================臨時文件寫入完畢========================
- randomFile = new RandomAccessFile(tmpfileName, "rw");
- //System.out.println(randomFile + "<br />");
- String theSingleDeli = randomFile.readLine(); //開始分界符
- String theSingleend = theSingleDeli + "--";
- //System.out.println(theSingleend);
- int k = 0;
- String line = "";
- boolean flag = true;
- long cntStartPoint = 0, cntEndPoint = 0;
- int count = 0;
- while (flag) {
- line = randomFile.readLine();
- if (line.indexOf("filename=/"") != -1) {
- String filename = ultool.getFileName(line);
- String filetype = ultool.getFileType(line);
- String elementname = ultool.getElename(line);
- //System.out.println("the filename and filetype and ename is :" + filename + "||" + filetype + "||" + elementname);
- line = randomFile.readLine();
- line = randomFile.readLine();
- cntStartPoint = randomFile.getFilePointer();
- boolean eofblock = false;
- while (!eofblock) {
- line = randomFile.readLine();
- //System.out.println("the line is :" + line);
- if (line.contains(theSingleDeli)) {
- eofblock = true;
- }
- }
- cntEndPoint = randomFile.getFilePointer() - line.length();
- int cntlen = (int)(cntEndPoint - cntStartPoint);
- System.out.println(cntlen + " || " + size);
- if ((cntlen != -1) && (cntlen >= size)) {
- description[count] = "上傳文件過大!";
- System.out.println("the description[" + count + "]" +
- description[count]);
- flag = false;
- } else {
- files = new byte[cntlen];
- randomFile.seek(cntStartPoint);
- randomFile.read(files, 0, cntlen);
- //System.out.println("the length is :" + ultool.getFormat(cntlen));
- String filelength = ultool.getFormat(cntlen);
- upload up =
- new upload(elementname, filetype, files, filename,
- filelength);
- names.add(up);
- //System.out.println(files);
- fields.put(elementname, count);
- }
- ++count;
- } else if ((k = line.indexOf("name=/"")) != -1) {
- String elementname = ultool.getElename(line);
- //System.out.println("the control name is :" + elementname);
- line = randomFile.readLine();
- line = randomFile.readLine();
- fields.put(elementname, line.toString());
- //System.out.println("the kongjian line is :" + line);
- }
- if (line.indexOf(theSingleend) != -1) {
- flag = false;
- }
- }
- randomFile.close();
- //刪除臨時文件
- File file = new File(tmpfileName);
- file.delete();
- //System.out.println(fields);
- }
- /**
- * 獲取上傳文件名
- * @param name 上傳文件控件名
- * @return
- */
- public String getFilename(String name) {
- if (name == null) {
- return "上傳文件有問題";
- }
- int index = (Integer)fields.get(name);
- upload up2 = (upload)names.get(index);
- return up2.filename;
- }
- /**
- * 獲取上傳文件的大小
- * @param name 上傳文件控件名
- * @return
- */
- public String getFileLength(String name) {
- if (name == null) {
- return null;
- } else {
- int index = (Integer)fields.get(name);
- upload up2 = (upload)names.get(index);
- return up2.filelength;
- }
- }
- /**
- * 獲取上傳文件類型
- * @param name 上傳文件控件名
- * @return
- */
- public String getContentType(String name) {
- if (name == null) {
- return "上傳文件有問題";
- } else {
- int index = (Integer)fields.get(name);
- upload up2 = (upload)names.get(index);
- return up2.Content_Type;
- }
- }
- /**
- * 獲取上傳文件Byte[]流
- * @param name 上傳文件控件名
- * @return byte[]
- */
- public byte[] getFileValue(String name) {
- if (name == null) {
- return null;
- } else {
- int index = (Integer)fields.get(name);
- upload up2 = (upload)names.get(index);
- return up2.value;
- }
- }
- /**
- * 獲取指定空間的值
- * @param fieldName 獲取表單控件名
- * @return String
- */
- public String getFieldValue(String fieldName) {
- if (fields == null || fieldName == null) {
- return null;
- }
- return (String)fields.get(fieldName);
- }
- //判斷上傳文件的類型
- public boolean canTransfer(int i) {
- suffix[i] = suffix[i].toLowerCase();
- //System.out.println("the suffix["+i+"] is :"+suffix[i]);
- if (sourceFile[i].equals("") ||
- (!(canSuffix.indexOf("." + suffix[i]) >= 0))) {
- description[i] = "文件類型不允許!";
- return false;
- } else {
- return true;
- }
- }
- class upload {
- // 控件名稱
- String elementname = null;
- // 類型
- String Content_Type = null;
- // 內容
- byte[] value = null;
- // 文件名
- String filename = null;
- // 文件大小
- String filelength = null;
- upload(String elementname, String Content_Type, byte[] value,
- String filename, String filelength) {
- this.elementname = new String(elementname);
- if (Content_Type != null)
- this.Content_Type = new String(Content_Type.trim());
- if (filename != null)
- this.filename = new String(filename.trim());
- if (value != null)
- this.value = value;
- if (filelength != null)
- this.filelength = filelength;
- }
- }
- class upFileInfo {
- /**
- * 得到對象
- * @param index 索引
- * @return 對象
- */
- upload getUpload(int index) {
- if ((index >= 0) && (names.size() > index)) {
- return (upload)names.elementAt(index);
- } else {
- return null;
- }
- }
- /**
- * 讀取內容
- * @param index 索引
- * @return 內容
- */
- byte[] getValue(int index) {
- upload up = getUpload(index);
- if (up == null) {
- return null;
- } else {
- return up.value;
- }
- }
- /**
- * 讀取文件名
- * @param index 索引
- * @return 文件名
- */
- String getFilename(int index) {
- upload up = getUpload(index);
- if (up == null) {
- return null;
- } else {
- return up.filename;
- }
- }
- /**
- * 讀取文件長度
- * @param index 索引
- * @return 文件長度
- */
- String getFileLength(int index) {
- upload up = getUpload(index);
- if (up == null) {
- return null;
- } else {
- return up.filelength;
- }
- }
- /**
- * 讀取文件類型
- * @param index 索引
- * @return 文件類型
- */
- String getFileType(int index) {
- upload up = getUpload(index);
- if (up == null) {
- return null;
- } else {
- return up.Content_Type;
- }
- }
- /**
- * 讀取控件名
- * @param index 索引
- * @return 控件名
- */
- String getElementName(int index) {
- upload up = getUpload(index);
- if (up == null) {
- return null;
- } else {
- return up.elementname;
- }
- }
- }
- }
- //get function
- package myupload;
- public class UpLoadTools {
- public UpLoadTools() {
- }
- /**
- * 獲取文件名稱
- * @param str String 一行字符串
- * @return String
- */
- public String getFileName(String str) {
- String pathName = str.substring(str.indexOf("filename="));
- int startIndex = pathName.indexOf("filename=/"") + 10;
- int endIndex = pathName.lastIndexOf("/"");
- if ((endIndex - startIndex) == 0)
- return "";
- else {
- startIndex = pathName.lastIndexOf("//") + 1;
- if ((startIndex != -1) && (startIndex != 0)) {
- pathName = pathName.substring(startIndex, endIndex);
- pathName=this.convert(pathName);
- } else {
- return "";
- }
- }
- return pathName;
- }
- /**
- * 獲取文件類型
- * @param str 一行文件
- * @return String
- */
- public String getFileType(String str) {
- String typeName = str.substring(str.indexOf("filename="));
- int startIndex = typeName.indexOf("filename=/"") + 10;
- int endIndex = typeName.lastIndexOf("/"");
- if ((endIndex - startIndex) == 0)
- return "";
- else {
- startIndex = typeName.lastIndexOf(".") + 1;
- if ((startIndex != -1) && (startIndex != 0)) {
- typeName = typeName.substring(startIndex, endIndex);
- } else {
- return "";
- }
- }
- return typeName;
- }
- /**
- * 獲取文件完整類型
- * @param str String 一行所讀出的字符串
- * @return String
- */
- public String getType(String str) {
- String typeName = null;
- typeName = str.substring(14);
- return typeName;
- }
- /**
- * 獲取控件名
- * @param str String 一行string
- * @return String
- */
- public String getElename(String str) {
- String elementName = null;
- String tempStr = str.substring(str.indexOf("name=/"") + 6);
- elementName = tempStr.substring(0, tempStr.indexOf("/""));
- return elementName;
- }
- /**
- * 四捨五入
- * @param f double 類型,要進行四捨五入的數字
- * @param position 要保留小數位的個數
- * @return String
- * @throws Exception
- */
- public String round(double f, int position) throws Exception {
- String sf = String.valueOf(f);
- int i = sf.indexOf(".");
- String s1 = "", s2 = "";
- if (sf.substring(i + 1).length() <= position) {
- return String.valueOf(f);
- }
- if (position == 0) {
- s1 = sf.substring(i - 1, i);
- s2 = sf.substring(i + position + 1, i + position + 2);
- if (Integer.parseInt(s2) >= 5) {
- s1 = String.valueOf(Integer.parseInt(s1) + 1);
- }
- return sf.substring(0, i - 1) + s1;
- } else {
- s1 = sf.substring(i + position, i + position + 1);
- s2 = sf.substring(i + position + 1, i + position + 2);
- if (Integer.parseInt(s2) >= 5) {
- s1 = String.valueOf(Integer.parseInt(s1) + 1);
- }
- return sf.substring(0, i + position) + s1;
- }
- }
- /**
- * 解決中中文顯示亂碼
- * @param str String 文件名
- * @return String
- */
- public String convert(String str) {
- try {
- byte[] bytesStr = str.getBytes("ISO-8859-1");
- return new String(bytesStr, "gb2312");
- } catch (Exception e) {
- return str;
- }
- }
- /**
- * 得到上傳文件大小
- * @param content String 上傳文件流
- * @return String
- */
- public String getFormat(int content) {
- String format = null;
- try {
- if (content > 1024 * 1024) {
- format = this.round(content / 1024 / 1024, 2) + "MB";
- } else if (content > 1024 && content < 1024 * 1024) {
- format = this.round(content / 1024, 2) + "KB";
- } else {
- format = content + "Bytes";
- }
- } catch (Exception e) {
- // TODO
- e.getMessage();
- format = "計算出錯";
- }
- return format;
- }
- /**
- * 獲取網頁頭部信息
- * @param line 獲取分隔符
- * @return boolean
- */
- public boolean getHeader(String line){
- boolean flag=false;
- String Str=line.substring(1,29);
- if(Str.equals("----------------------------")){
- flag=true;
- }else{
- flag=false;
- }
- return flag;
- }
- }
- //使用方法
- UpLoadBean ulb = new UpLoadBean(request);
- ulb.setSize(1024*1024);
- ulb.getSourceFile();
- String username = ulb.getFieldValue("username");
- String userpwd = ulb.getFieldValue("userpwd");
- String pfile = "filename1";
- byte[] filename1 = ulb.getFileValue(pfile);
- String filename = ulb.getFilename(pfile);
- String filetype = ulb.getContentType(pfile);
- String filelength = ulb.getFileLength(pfile);
- String pfile1 = "filename2";
- byte[] filename12 = ulb.getFileValue(pfile1);
- String filename2 = ulb.getFilename(pfile1);
- String filetype2 = ulb.getContentType(pfile1);
- String filelength2 = ulb.getFileLength(pfile1);
- try {
- InitialContext ic = new InitialContext();
- DataSource ds = (DataSource)ic.lookup("jdbc/oldwolfDS");
- Connection conn = ds.getConnection();
- String sql="insert into uptable (username,userpwd,pic1) values (?,?,empty_blob())";
- //第一步插入一個空Blob字段
- PreparedStatement ps = conn.prepareStatement(sql);
- ps.setString(1, username);
- ps.setString(2, userpwd);
- ps.executeUpdate();
- ps.close();
- //第二步取出數據庫表中的Blob字段。
- Statement st = conn.createStatement();
- String sql1="select pic1 from uptable where username='" + username + "' for update";
- ResultSet rs = st.executeQuery(sql1);
- rs.next();
- Blob blob1 = (Blob)rs.getBlob("pic1");
- //Blob更新操作:設置輸出流。
- OutputStream os1 = blob1.setBinaryStream(0);
- //System.out.println("the sql is :"+sql+" || the sql1 is :"+sql1+" || the blob1 is :"+blob1+" || the blob2 is :"+blob2+" || the os1 is :"+os1+" || the os2 is :"+os2);
- os1.write(filename1);
- os1.close();
- //Blob更新操作:通過輸出流寫入內容。
- ps = conn.prepareStatement("update uptable set pic1=? where username='" +username + "'");
- ps.setBlob(1, blob1);
- conn.commit();
- ps.close();
- rs.close();
- st.close();conn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
這個程序是我自己寫的,還有些問題,比如說上傳文件大小的限制,類型的限制還沒做好.希望大家一起來完成.
希望這個程序能對初學者有所幫組