j2ee上傳文件自制組件

 

 

上傳文件組件說明

 

 

上傳組件設計思想:

 

     這裏的自制上傳組件用的是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中的上傳文件的大小

 

 

 

 

 

以下附上源碼:

 

  1. //upload javabean
  2. package myupload;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.RandomAccessFile;
  7. import java.util.Hashtable;
  8. import java.util.Vector;
  9. import javax.servlet.RequestDispatcher;
  10. import javax.servlet.ServletInputStream;
  11. import javax.servlet.http.Cookie;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpSession;
  14. public class UpLoadBean {
  15.     private HttpServletRequest request = null;
  16.     public UpLoadBean(HttpServletRequest request) {
  17.         this.request = request;
  18.     }
  19.     //方法重載
  20.     public Object getAttribute(String name) {
  21.         return request.getAttribute(name);
  22.     }
  23.     public java.util.Enumeration getAttributeNames() {
  24.         return request.getAttributeNames();
  25.     }
  26.     public java.lang.String getCharacterEncoding() {
  27.         return request.getCharacterEncoding();
  28.     }
  29.     public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException {
  30.         request.setCharacterEncoding(env);
  31.     }
  32.     public int getContentLength() {
  33.         return request.getContentLength();
  34.     }
  35.     public int getLocalPort() {
  36.         return request.getLocalPort();
  37.     }
  38.     public String getLocalAddr() {
  39.         return request.getLocalAddr();
  40.     }
  41.     public String getLocalName() {
  42.         return request.getLocalName();
  43.     }
  44.     public int getRemotePort() {
  45.         return request.getRemotePort();
  46.     }
  47.     public java.lang.String getContentType() {
  48.         return request.getContentType();
  49.     }
  50.     public ServletInputStream getInputStream() throws java.io.IOException {
  51.         return request.getInputStream();
  52.     }
  53.     public java.util.Map getParameterMap() {
  54.         return request.getParameterMap();
  55.     }
  56.     public java.lang.String getProtocol() {
  57.         return request.getProtocol();
  58.     }
  59.     public java.lang.String getScheme() {
  60.         return request.getScheme();
  61.     }
  62.     public java.lang.String getServerName() {
  63.         return request.getServerName();
  64.     }
  65.     public int getServerPort() {
  66.         return request.getServerPort();
  67.     }
  68.     public java.io.BufferedReader getReader() throws java.io.IOException {
  69.         return request.getReader();
  70.     }
  71.     public java.lang.String getRemoteAddr() {
  72.         return request.getRemoteAddr();
  73.     }
  74.     public java.lang.String getRemoteHost() {
  75.         return request.getRemoteHost();
  76.     }
  77.     public void setAttribute(java.lang.String name, Object o) {
  78.         request.setAttribute(name, o);
  79.     }
  80.     public void removeAttribute(java.lang.String name) {
  81.         request.removeAttribute(name);
  82.     }
  83.     public java.util.Locale getLocale() {
  84.         return request.getLocale();
  85.     }
  86.     public java.util.Enumeration getLocales() {
  87.         return request.getLocales();
  88.     }
  89.     public boolean isSecure() {
  90.         return request.isSecure();
  91.     }
  92.     public RequestDispatcher getRequestDispatcher(String path) {
  93.         return request.getRequestDispatcher(path);
  94.     }
  95.     public java.lang.String getRealPath(String path) {
  96.         return request.getRealPath(path);
  97.     }
  98.     public java.lang.String getAuthType() {
  99.         return request.getAuthType();
  100.     }
  101.     public Cookie[] getCookies() {
  102.         return request.getCookies();
  103.     }
  104.     public long getDateHeader(java.lang.String name) {
  105.         return request.getDateHeader(name);
  106.     }
  107.     public java.lang.String getHeader(java.lang.String name) {
  108.         return request.getHeader(name);
  109.     }
  110.     public java.util.Enumeration getHeaders(java.lang.String name) {
  111.         return request.getHeaders(name);
  112.     }
  113.     public java.util.Enumeration getHeaderNames() {
  114.         return request.getHeaderNames();
  115.     }
  116.     public int getIntHeader(java.lang.String name) {
  117.         return request.getIntHeader(name);
  118.     }
  119.     public java.lang.String getPathInfo() {
  120.         return request.getPathInfo();
  121.     }
  122.     public java.lang.String getPathTranslated() {
  123.         return request.getPathTranslated();
  124.     }
  125.     public java.lang.String getContextPath() {
  126.         return request.getContextPath();
  127.     }
  128.     public java.lang.String getQueryString() {
  129.         return request.getQueryString();
  130.     }
  131.     public java.lang.String getRemoteUser() {
  132.         return request.getRemoteUser();
  133.     }
  134.     public boolean isUserInRole(java.lang.String role) {
  135.         return request.isUserInRole(role);
  136.     }
  137.     public java.security.Principal getUserPrincipal() {
  138.         return request.getUserPrincipal();
  139.     }
  140.     public java.lang.String getRequestedSessionId() {
  141.         return request.getRequestedSessionId();
  142.     }
  143.     public java.lang.String getRequestURI() {
  144.         return request.getRequestURI();
  145.     }
  146.     public java.lang.StringBuffer getRequestURL() {
  147.         return request.getRequestURL();
  148.     }
  149.     public java.lang.String getServletPath() {
  150.         return request.getServletPath();
  151.     }
  152.     public HttpSession getSession() {
  153.         return request.getSession();
  154.     }
  155.     public HttpSession getSession(boolean create) {
  156.         return request.getSession(create);
  157.     }
  158.     public boolean isRequestedSessionIdValid() {
  159.         return request.isRequestedSessionIdValid();
  160.     }
  161.     public boolean isRequestedSessionIdFromCookie() {
  162.         return request.isRequestedSessionIdFromCookie();
  163.     }
  164.     public boolean isRequestedSessionIdFromURL() {
  165.         return request.isRequestedSessionIdFromURL();
  166.     }
  167.     public boolean isRequestedSessionIdFromUrl() {
  168.         return request.isRequestedSessionIdFromUrl();
  169.     }
  170.     //重載結束
  171.     //實例化一個tool
  172.     UpLoadTools ultool = new UpLoadTools();
  173.     private String[] sourceFile = new String[255]; //源文件名
  174.     private String[] suffix = new String[255]; //文件後綴名
  175.     private String canSuffix = ".gif.jpg.jpeg.png"//可上傳的文件後綴名
  176.     private byte[] files = null//上傳文件數組
  177.     private ServletInputStream inputStream = null//輸入流 
  178.     private int streamLenth = 0//輸入流長度
  179.     private FileOutputStream tmpfileStream = null//臨時文件
  180.     private RandomAccessFile randomFile = null//以隨機讀寫方式打開http臨時流文件
  181.     private String[] description = new String[255]; //描述狀態
  182.     private long size = 1024 * 1024 * 300//限制大小 若爲-1則不限制
  183.     // 保存名字/對象對應關係
  184.     private Hashtable fields = new Hashtable(); //hashtable
  185.     // 保存所有名字
  186.     private Vector names = new Vector(); //vector
  187.     //上傳文件限制
  188.     public void setSuffix(String canSuffix) {
  189.         this.canSuffix = canSuffix;
  190.     }
  191.     //上傳文件大小限制
  192.     public void setSize(long maxSize) {
  193.         this.size = maxSize;
  194.         System.out.println("新配置" + size + " || 傳過來的參數:" + maxSize);
  195.     }
  196.     //上傳文件主方法
  197.     public void getSourceFile() throws IOException {
  198.         inputStream = request.getInputStream();
  199.         //System.out.println(inputStream + "<br />");
  200.         //==============將上傳文件存入臨時文件=======================
  201.         String tmpfileName = null;
  202.         streamLenth = request.getContentLength();
  203.         tmpfileName = "c://temp//" + request.getSession().getId();
  204.         tmpfileStream = new FileOutputStream(tmpfileName);
  205.         //獲取上傳內容,並將其保存在臨時文件中。
  206.         int bytesRead = 0, totalBytes = 0;
  207.         byte[] cnt;
  208.         while (totalBytes < streamLenth) {
  209.             cnt = new byte[256];
  210.             bytesRead = 
  211.                     inputStream.read(cnt, 0256); //中的方法在此字節輸入流中從給定的偏移量開始將各字節讀取到指定的 byte 數組中
  212.             totalBytes += bytesRead;
  213.             tmpfileStream.write(cnt);
  214.         }
  215.         tmpfileStream.close();
  216.         inputStream.close();
  217.         //現已將Http協議上傳的內容全部寫入了臨時文件。以下的代碼便可在服務器上對上傳的內容進行解釋
  218.         //======================臨時文件寫入完畢========================
  219.         randomFile = new RandomAccessFile(tmpfileName, "rw");
  220.         //System.out.println(randomFile + "<br />");
  221.         String theSingleDeli = randomFile.readLine(); //開始分界符
  222.         String theSingleend = theSingleDeli + "--";
  223.         //System.out.println(theSingleend);
  224.         int k = 0;
  225.         String line = "";
  226.         boolean flag = true;
  227.         long cntStartPoint = 0, cntEndPoint = 0;
  228.         int count = 0;
  229.         while (flag) {
  230.             line = randomFile.readLine();
  231.             if (line.indexOf("filename=/"") != -1) {
  232.                 String filename = ultool.getFileName(line);
  233.                 String filetype = ultool.getFileType(line);
  234.                 String elementname = ultool.getElename(line);
  235.                 //System.out.println("the filename and filetype and ename is :" + filename + "||" + filetype + "||" + elementname);
  236.                 line = randomFile.readLine();
  237.                 line = randomFile.readLine();
  238.                 cntStartPoint = randomFile.getFilePointer();
  239.                 boolean eofblock = false;
  240.                 while (!eofblock) {
  241.                     line = randomFile.readLine();
  242.                     //System.out.println("the line is :" + line);
  243.                     if (line.contains(theSingleDeli)) {
  244.                         eofblock = true;
  245.                     }
  246.                 }
  247.                 cntEndPoint = randomFile.getFilePointer() - line.length();
  248.                 int cntlen = (int)(cntEndPoint - cntStartPoint);
  249.                 System.out.println(cntlen + " || " + size);
  250.                 if ((cntlen != -1) && (cntlen >= size)) {
  251.                     description[count] = "上傳文件過大!";
  252.                     System.out.println("the description[" + count + "]" + 
  253.                                        description[count]);
  254.                     flag = false;
  255.                 } else {
  256.                     files = new byte[cntlen];
  257.                     randomFile.seek(cntStartPoint);
  258.                     randomFile.read(files, 0, cntlen);
  259.                     //System.out.println("the length is :" + ultool.getFormat(cntlen));
  260.                     String filelength = ultool.getFormat(cntlen);
  261.                     upload up = 
  262.                         new upload(elementname, filetype, files, filename, 
  263.                                    filelength);
  264.                     names.add(up);
  265.                     //System.out.println(files);
  266.                     fields.put(elementname, count);
  267.                 }
  268.                 ++count;
  269.             } else if ((k = line.indexOf("name=/"")) != -1) {
  270.                 String elementname = ultool.getElename(line);
  271.                 //System.out.println("the control name is :" + elementname);
  272.                 line = randomFile.readLine();
  273.                 line = randomFile.readLine();
  274.                 fields.put(elementname, line.toString());
  275.                 //System.out.println("the kongjian line is :" + line);
  276.             }
  277.             if (line.indexOf(theSingleend) != -1) {
  278.                 flag = false;
  279.             }
  280.         }
  281.         randomFile.close();
  282.         //刪除臨時文件
  283.         File file = new File(tmpfileName);
  284.         file.delete();
  285.         //System.out.println(fields);
  286.     }
  287.     /**
  288.      * 獲取上傳文件名
  289.      * @param name 上傳文件控件名
  290.      * @return
  291.      */
  292.     public String getFilename(String name) {
  293.         if (name == null) {
  294.             return "上傳文件有問題";
  295.         }
  296.         int index = (Integer)fields.get(name);
  297.         upload up2 = (upload)names.get(index);
  298.         return up2.filename;
  299.     }
  300.     /**
  301.      * 獲取上傳文件的大小
  302.      * @param name 上傳文件控件名
  303.      * @return
  304.      */
  305.     public String getFileLength(String name) {
  306.         if (name == null) {
  307.             return null;
  308.         } else {
  309.             int index = (Integer)fields.get(name);
  310.             upload up2 = (upload)names.get(index);
  311.             return up2.filelength;
  312.         }
  313.     }
  314.     /**
  315.      * 獲取上傳文件類型
  316.      * @param name 上傳文件控件名
  317.      * @return
  318.      */
  319.     public String getContentType(String name) {
  320.         if (name == null) {
  321.             return "上傳文件有問題";
  322.         } else {
  323.             int index = (Integer)fields.get(name);
  324.             upload up2 = (upload)names.get(index);
  325.             return up2.Content_Type;
  326.         }
  327.     }
  328.     /**
  329.      * 獲取上傳文件Byte[]流
  330.      * @param name 上傳文件控件名
  331.      * @return byte[]
  332.      */
  333.     public byte[] getFileValue(String name) {
  334.         if (name == null) {
  335.             return null;
  336.         } else {
  337.             int index = (Integer)fields.get(name);
  338.             upload up2 = (upload)names.get(index);
  339.             return up2.value;
  340.         }
  341.     }
  342.     /**
  343.      * 獲取指定空間的值
  344.      * @param fieldName 獲取表單控件名
  345.      * @return String
  346.      */
  347.     public String getFieldValue(String fieldName) {
  348.         if (fields == null || fieldName == null) {
  349.             return null;
  350.         }
  351.         return (String)fields.get(fieldName);
  352.     }
  353.     //判斷上傳文件的類型
  354.     public boolean canTransfer(int i) {
  355.         suffix[i] = suffix[i].toLowerCase();
  356.         //System.out.println("the suffix["+i+"] is :"+suffix[i]);
  357.         if (sourceFile[i].equals("") || 
  358.             (!(canSuffix.indexOf("." + suffix[i]) >= 0))) {
  359.             description[i] = "文件類型不允許!";
  360.             return false;
  361.         } else {
  362.             return true;
  363.         }
  364.     }
  365.     class upload {
  366.         // 控件名稱
  367.         String elementname = null;
  368.         // 類型
  369.         String Content_Type = null;
  370.         // 內容
  371.         byte[] value = null;
  372.         // 文件名
  373.         String filename = null;
  374.         // 文件大小
  375.         String filelength = null;
  376.         upload(String elementname, String Content_Type, byte[] value, 
  377.                String filename, String filelength) {
  378.             this.elementname = new String(elementname);
  379.             if (Content_Type != null)
  380.                 this.Content_Type = new String(Content_Type.trim());
  381.             if (filename != null)
  382.                 this.filename = new String(filename.trim());
  383.             if (value != null)
  384.                 this.value = value;
  385.             if (filelength != null)
  386.                 this.filelength = filelength;
  387.         }
  388.     }
  389.     class upFileInfo {
  390.         /**
  391.          * 得到對象
  392.          * @param index 索引
  393.          * @return 對象
  394.          */
  395.         upload getUpload(int index) {
  396.             if ((index >= 0) && (names.size() > index)) {
  397.                 return (upload)names.elementAt(index);
  398.             } else {
  399.                 return null;
  400.             }
  401.         }
  402.         /**
  403.          * 讀取內容
  404.          * @param index 索引
  405.          * @return 內容
  406.          */
  407.         byte[] getValue(int index) {
  408.             upload up = getUpload(index);
  409.             if (up == null) {
  410.                 return null;
  411.             } else {
  412.                 return up.value;
  413.             }
  414.         }
  415.         /**
  416.          * 讀取文件名
  417.          * @param index 索引
  418.          * @return 文件名
  419.          */
  420.         String getFilename(int index) {
  421.             upload up = getUpload(index);
  422.             if (up == null) {
  423.                 return null;
  424.             } else {
  425.                 return up.filename;
  426.             }
  427.         }
  428.         /**
  429.          * 讀取文件長度
  430.          * @param index 索引
  431.          * @return 文件長度
  432.          */
  433.         String getFileLength(int index) {
  434.             upload up = getUpload(index);
  435.             if (up == null) {
  436.                 return null;
  437.             } else {
  438.                 return up.filelength;
  439.             }
  440.         }
  441.         /**
  442.          * 讀取文件類型
  443.          * @param index 索引
  444.          * @return 文件類型
  445.          */
  446.         String getFileType(int index) {
  447.             upload up = getUpload(index);
  448.             if (up == null) {
  449.                 return null;
  450.             } else {
  451.                 return up.Content_Type;
  452.             }
  453.         }
  454.         /**
  455.          * 讀取控件名
  456.          * @param index 索引
  457.          * @return 控件名
  458.          */
  459.         String getElementName(int index) {
  460.             upload up = getUpload(index);
  461.             if (up == null) {
  462.                 return null;
  463.             } else {
  464.                 return up.elementname;
  465.             }
  466.         }
  467.     }
  468. }

 

  1. //get function 
  2. package myupload;
  3. public class UpLoadTools {
  4.     public UpLoadTools() {
  5.     }
  6.     
  7.     /**
  8.      * 獲取文件名稱
  9.      * @param str String 一行字符串
  10.      * @return String
  11.      */
  12.     public String getFileName(String str) {
  13.         String pathName = str.substring(str.indexOf("filename="));
  14.         int startIndex = pathName.indexOf("filename=/"") + 10;
  15.         int endIndex = pathName.lastIndexOf("/"");
  16.         if ((endIndex - startIndex) == 0)
  17.             return "";
  18.         else {
  19.             startIndex = pathName.lastIndexOf("//") + 1;
  20.             if ((startIndex != -1) && (startIndex != 0)) {
  21.                 pathName = pathName.substring(startIndex, endIndex);
  22.                 pathName=this.convert(pathName);
  23.             } else {
  24.                 return "";
  25.             }
  26.         }
  27.         return pathName;
  28.     }
  29.     /**
  30.      * 獲取文件類型
  31.      * @param str 一行文件
  32.      * @return String
  33.      */
  34.     public String getFileType(String str) {
  35.         String typeName = str.substring(str.indexOf("filename="));
  36.         int startIndex = typeName.indexOf("filename=/"") + 10;
  37.         int endIndex = typeName.lastIndexOf("/"");
  38.         if ((endIndex - startIndex) == 0)
  39.             return "";
  40.         else {
  41.             startIndex = typeName.lastIndexOf(".") + 1;
  42.             if ((startIndex != -1) && (startIndex != 0)) {
  43.                 typeName = typeName.substring(startIndex, endIndex);
  44.             } else {
  45.                 return "";
  46.             }
  47.         }
  48.         return typeName;
  49.     }
  50.     /**
  51.      * 獲取文件完整類型
  52.      * @param str String 一行所讀出的字符串
  53.      * @return String
  54.      */
  55.     public String getType(String str) {
  56.         String typeName = null;
  57.         typeName = str.substring(14);
  58.         return typeName;
  59.     }
  60.     /**
  61.      * 獲取控件名
  62.      * @param str String 一行string
  63.      * @return String
  64.      */
  65.     public String getElename(String str) {
  66.         String elementName = null;
  67.         String tempStr = str.substring(str.indexOf("name=/"") + 6);
  68.         elementName = tempStr.substring(0, tempStr.indexOf("/""));
  69.         return elementName;
  70.     }
  71.     /**   
  72.      *   四捨五入   
  73.      *   @param f double 類型,要進行四捨五入的數字   
  74.      *   @param position 要保留小數位的個數   
  75.      *   @return String   
  76.      *   @throws Exception   
  77.      */
  78.     public String round(double f, int position) throws Exception {
  79.         String sf = String.valueOf(f);
  80.         int i = sf.indexOf(".");
  81.         String s1 = "", s2 = "";
  82.         if (sf.substring(i + 1).length() <= position) {
  83.             return String.valueOf(f);
  84.         }
  85.         if (position == 0) {
  86.             s1 = sf.substring(i - 1, i);
  87.             s2 = sf.substring(i + position + 1, i + position + 2);
  88.             if (Integer.parseInt(s2) >= 5) {
  89.                 s1 = String.valueOf(Integer.parseInt(s1) + 1);
  90.             }
  91.             return sf.substring(0, i - 1) + s1;
  92.         } else {
  93.             s1 = sf.substring(i + position, i + position + 1);
  94.             s2 = sf.substring(i + position + 1, i + position + 2);
  95.             if (Integer.parseInt(s2) >= 5) {
  96.                 s1 = String.valueOf(Integer.parseInt(s1) + 1);
  97.             }
  98.             return sf.substring(0, i + position) + s1;
  99.         }
  100.     }
  101.     /**
  102.      * 解決中中文顯示亂碼
  103.      * @param str String 文件名
  104.      * @return String
  105.      */
  106.     public String convert(String str) {
  107.         try {
  108.             byte[] bytesStr = str.getBytes("ISO-8859-1");
  109.             return new String(bytesStr, "gb2312");
  110.         } catch (Exception e) {
  111.             return str;
  112.         }
  113.     }
  114.     /**
  115.      * 得到上傳文件大小
  116.      * @param content String 上傳文件流
  117.      * @return String
  118.      */
  119.     public String getFormat(int content) {
  120.         String format = null;
  121.         try {
  122.             if (content > 1024 * 1024) {
  123.                 format = this.round(content / 1024 / 10242) + "MB";
  124.             } else if (content > 1024 && content < 1024 * 1024) {
  125.                 format = this.round(content / 10242) + "KB";
  126.             } else {
  127.                 format = content + "Bytes";
  128.             }
  129.         } catch (Exception e) {
  130.             // TODO
  131.             e.getMessage();
  132.             format = "計算出錯";
  133.         }
  134.         return format;
  135.     }
  136.     /**
  137.      * 獲取網頁頭部信息
  138.      * @param line 獲取分隔符
  139.      * @return boolean
  140.      */
  141.     public boolean getHeader(String line){
  142.         boolean flag=false;
  143.         String Str=line.substring(1,29);
  144.         if(Str.equals("----------------------------")){
  145.             flag=true;
  146.         }else{
  147.             flag=false;
  148.         }
  149.         return flag;
  150.     }
  151. }

 
  1. //使用方法
  2.         UpLoadBean ulb = new UpLoadBean(request);
  3.         ulb.setSize(1024*1024);
  4.         ulb.getSourceFile();
  5.         
  6.         String username = ulb.getFieldValue("username");
  7.         String userpwd = ulb.getFieldValue("userpwd");
  8.         String pfile = "filename1";
  9.         byte[] filename1 = ulb.getFileValue(pfile);
  10.         String filename = ulb.getFilename(pfile);
  11.         String filetype = ulb.getContentType(pfile);
  12.         String filelength = ulb.getFileLength(pfile);
  13.        
  14.         String pfile1 = "filename2";
  15.         byte[] filename12 = ulb.getFileValue(pfile1);
  16.         String filename2 = ulb.getFilename(pfile1);
  17.         String filetype2 = ulb.getContentType(pfile1);
  18.         String filelength2 = ulb.getFileLength(pfile1);
  19.         
  20.                 try {
  21.              InitialContext ic = new InitialContext();
  22.              DataSource ds = (DataSource)ic.lookup("jdbc/oldwolfDS");
  23.              Connection conn = ds.getConnection();
  24.              String sql="insert into uptable (username,userpwd,pic1) values (?,?,empty_blob())";
  25.              //第一步插入一個空Blob字段
  26.              PreparedStatement ps = conn.prepareStatement(sql);
  27.              ps.setString(1, username);
  28.              ps.setString(2, userpwd);
  29.              ps.executeUpdate();
  30.              ps.close();
  31.              //第二步取出數據庫表中的Blob字段。
  32.              Statement st = conn.createStatement();
  33.              String sql1="select pic1 from uptable where username='" + username + "' for update";
  34.              ResultSet rs = st.executeQuery(sql1);
  35.              rs.next();
  36.              Blob blob1 = (Blob)rs.getBlob("pic1");
  37.              //Blob更新操作:設置輸出流。
  38.              OutputStream os1 = blob1.setBinaryStream(0);
  39.              //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);
  40.              os1.write(filename1);
  41.              os1.close();
  42.              //Blob更新操作:通過輸出流寫入內容。
  43.              ps = conn.prepareStatement("update uptable set pic1=? where username='" +username + "'");
  44.              ps.setBlob(1, blob1);
  45.              conn.commit();
  46.              ps.close();
  47.              rs.close();
  48.              st.close();conn.close();
  49.          } catch (Exception e) {
  50.              e.printStackTrace();
  51.          }

這個程序是我自己寫的,還有些問題,比如說上傳文件大小的限制,類型的限制還沒做好.希望大家一起來完成.

希望這個程序能對初學者有所幫組

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章