Java Blog From WeiChunHua

          Java

          常用鏈接

          統計

          develop

          news

          最新評論

          java文件上傳代碼

          1 package com.khan.web;
             2
             3 import java.io.DataInputStream;
             4 import java.io.File;
             5 import java.io.FileNotFoundException;
             6 import java.io.FileOutputStream;
             7 import java.io.IOException;
             8 import javax.servlet.http.HttpServletRequest;
             9 import java.io.*;
          10 import java.util.HashMap;
          11
          12
          13 public class uploadFile   {
          14      public static final int MAX_SIZE = 1024 * 1024*100;
          15      public static final String FILE_DIR = "d:/temp/";
          16
          17      private int file_Size=0;
          18      private String file_Path = "";
          19      private HashMap hm = new HashMap();
          20
          21      public String upLoad(HttpServletRequest req) {
          22          String tmpString ="";
          23          String result = "";
          24          DataInputStream dis = null;
          25          String split_Str = "";
          26
          27          try {
          28              dis = new DataInputStream(req.getInputStream());
          29              String content = req.getContentType();
          30              if (content != null && content.indexOf("multipart/form-data") != -1) {
          31
          32                  int reqSize = req.getContentLength();
          33                  byte[] data = new byte[reqSize];
          34                  int bytesRead = 0;
          35                  int totalBytesRead = 0;
          36                  int sizeCheck = 0;
          37                  while (totalBytesRead < reqSize) {
          38                      // check for maximum file size violation
          39                      sizeCheck = totalBytesRead + dis.available();
          40                      if (sizeCheck > MAX_SIZE)
          41                          result = "文件太大不能上傳";
          42
          43                      bytesRead = dis.read(data, totalBytesRead, reqSize);
          44                      totalBytesRead += bytesRead;
          45                  }
          46                  String dataString = null;
          47                  //dataString = new String(data, "ISO-8859-1");
          48                  dataString = new String(data);
          49                  tmpString = new String(data);
          50                  hm = parseAnotherParam(tmpString);
          51                
          52                  //取出字段分割符
          53                  split_Str = dataString.substring(0, dataString.indexOf("\r\n"));
          54                  // 分離filepath 并賦值
          55                  dataString = dataString.substring(dataString.indexOf("filename=\""));
          56                  String filePath = dataString.substring(0, dataString.indexOf("Content-Type:"));
          57                  if (filePath==null && filePath.equals("")) return "";
          58                  //System.out.println(filePath);
          59                  dataString = new String(dataString.getBytes(),"ISO-8859-1");
          60                  // 分離contentType 并賦值
          61                  dataString = dataString.substring(dataString.indexOf("Content-Type:") + 1);
          62                  dataString = dataString.substring(dataString.indexOf("\n") + 1);
          63                  // 分離文件信息 獲得最終想要的字節
          64 //System.out.print("|"+dataString+"|");
          65                  dataString = dataString.substring(2, dataString.indexOf(split_Str));
          66 //System.out.println("|"+dataString+"|");
          67                  dataString = dataString.substring(0, dataString.lastIndexOf("\n") - 1);
          68 //System.out.print("|"+dataString+"|");
          69                  if (writeFile(dataString.getBytes("ISO-8859-1"), FILE_DIR + getFileName(filePath))) {
          70                      this.file_Size = dataString.getBytes("ISO-8859-1").length;
          71                      this.file_Path = FILE_DIR + getFileName(filePath);
          72                      result = "文件上傳完畢";
          73                  } else {
          74                      result = "文件上傳失敗";
          75                  }
          76              } else {
          77                  result = "content 必須為 multipart/form-data";
          78              }
          79          } catch (UnsupportedEncodingException ex4) {
          80              result = "getBytes 失敗 UnsupportedEncodingException錯誤";
          81          } catch (NullPointerException e) {
          82              result = "getBytes 失敗 NullPointerException錯誤";
          83          } catch (IOException ex1) {
          84              result = "IOException 錯誤 ";
          85          }
          86
          87          return result;
          88      }
          89
          90      public String getFilePath(){
          91          return this.file_Path;
          92      }
          93
          94      public int getFileSize(){
          95          return this.file_Size;
          96      }
          97
          98      public boolean writeFile(byte[] data, String path) {
          99          File f = null;
          100          FileOutputStream fos = null;
          101          try {
          102              f = new File(path);
          103              f.createNewFile();
          104              fos = new FileOutputStream(f);
          105              fos.write(data, 0, data.length);
          106          } catch (FileNotFoundException e) {
          107              return false;
          108          } catch (IOException e) {
          109              return false;
          110          } finally {
          111              try {
          112                  fos.close();
          113              } catch (IOException e) {
          114                  return false;
          115              }
          116          }
          117          return true;
          118      }
          119
          120      public String getFileName(String arg) {
          121          String path = "";
          122          if (arg.indexOf("\"") > -1)
          123              path = arg.substring(arg.indexOf("\"") + 1, arg.lastIndexOf("\""));
          124          else
          125              path = arg;
          126      //System.out.println("file_path:"+arg);
          127          path = path.substring(path.lastIndexOf("\\") + 1);
          128          return path;
          129      }
          130
          131
          132      public HashMap parseAnotherParam(String str){
          133        HashMap hm= new HashMap();
          134        String key="";
          135        String value="";
          136        int startindex = 0;
          137        int endindex = 0;
          138
          139        startindex = str.indexOf("Content-Disposition: form-data; name=\"") + "Content-Disposition: form-data; name=\"".length();
          140        endindex = str.indexOf("\"\r\n\r\n");
          141
          142        while ( startindex >-1 && endindex > -1 ){
          143          key = str.substring(startindex, endindex);
          144
          145          if(!str.substring(endindex , endindex + 5).equals("\"\r\n\r\n")   ){//去掉沒有value的元素
          146              str = str.substring(endindex);
          147              startindex = str.indexOf("Content-Disposition: form-data; name=\"") + "Content-Disposition: form-data; name=\"".length();
          148              endindex = str.indexOf("\"\r\n\r\n");
          149              continue;
          150          }
          151          if( key.indexOf("\";") > -1){//去掉上傳文件的參數以及編碼
          152             str = str.substring(str.indexOf("\";") + 2);
          153             startindex = str.indexOf("Content-Disposition: form-data; name=\"") + "Content-Disposition: form-data; name=\"".length();
          154             endindex = str.indexOf("\"\r\n\r\n");
          155
          156             continue;
          157          } else
          158              str = str.substring(endindex + 5);
          159
          160          value = str.substring(0, str.indexOf("\r\n"));
          161          str = str.substring(str.indexOf("\r\n") + 2);
          162          //System.out.println("key:"+key+" value:"+value);
          163          hm.put(key,value);
          164
          165          startindex = str.indexOf("Content-Disposition: form-data; name=\"") + "Content-Disposition: form-data; name=\"".length();
          166          endindex = str.indexOf("\"\r\n\r\n");
          167
          168        }
          169        return hm;
          170      }
          171
          172      public String getParameter(String param){
          173          //System.out.println(hm.toString());
          174        return (String)hm.get(param);
          175      }
          176
          177
          178 }

          posted on 2008-06-30 11:10 sunny spring 閱讀(5301) 評論(1)  編輯  收藏 所屬分類: javaee

          評論

          # re: java文件上傳代碼 2008-07-01 12:56 思春貼調查員(Khan)

          樓主不厚道. 轉載請著名來源.
          其二. 這篇代碼不夠完善.傳輸二進制文件時有bug.. 若要直接引用請參閱
          http://www.cppblog.com/Khan/archive/2008/06/18/11132.html,   回復  更多評論   

          主站蜘蛛池模板: 犍为县| 美姑县| 广饶县| 黔东| 焦作市| 霸州市| 桃源县| 宜兰县| 武功县| 兰坪| 科技| 清水县| 乌鲁木齐县| 台山市| 琼结县| 泰安市| 高唐县| 灵台县| 诸暨市| 白山市| 张掖市| 洛宁县| 谢通门县| 莱阳市| 安西县| 苍南县| 阿荣旗| 泰安市| 贺兰县| 五峰| 万安县| 镇雄县| 宣化县| 黄山市| 松溪县| 天台县| 清远市| 嵊泗县| 本溪市| 金湖县| 宣武区|