我的漫漫程序之旅

          專注于JavaWeb開發
          隨筆 - 39, 文章 - 310, 評論 - 411, 引用 - 0
          數據加載中……

          HttpURLConnection上傳文件(圖片)小試

          需求:用HttpURLConnection模擬上傳圖片并把圖片的名稱也要傳遞過去.

          簡單分析:寫入流的時候依次寫入 圖片名稱 + "|" 分隔符 +  圖片流

          然后服務器接收的再處理流.分別取出圖片名和圖片.

          /**
               * 上傳方法
               * 返回上傳完畢的文件名
               * *
               
          */

              
          public String upload(File f)
              
          {
                  
          try
                  
          {
                      
          //服務器IP(這里是從屬性文件中讀取出來的)
                      String hostip = FileSupport.getServerIP();
                      URL url 
          = new URL("http://"+ hostip +"/oxServer/ReceiveServlet");
                      
                      HttpURLConnection uc 
          = (HttpURLConnection) url.openConnection();
                      
          //上傳圖片的一些參數設置
                      uc
                              .setRequestProperty(
                                      
          "Accept",
                                      
          "image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");
                      uc.setRequestProperty(
          "Accept-Language""zh-cn");
                      uc
                              .setRequestProperty(
          "Content-type",
                                      
          "multipart/form-data;   boundary=---------------------------7d318fd100112");
                      uc.setRequestProperty(
          "Accept-Encoding""gzip,   deflate");
                      uc
                              .setRequestProperty(
          "User-Agent",
                                      
          "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
                      uc.setRequestProperty(
          "Connection""Keep-Alive");
                      uc.setDoOutput(
          true);
                      uc.setUseCaches(
          true);
                  
                      
          //讀取文件流
                      int size = (int) f.length();
                      
          byte[] data = new byte[size];
                      FileInputStream fis 
          = new FileInputStream(f);
                      OutputStream out 
          = uc.getOutputStream();
                      fis.read(data, 
          0, size);
                      
          //寫入文件名
                      out.write(f.getName().trim().getBytes());
                      
          //寫入分隔符
                      out.write('|');
                      
          //寫入圖片流
                      out.write(data);
                      out.flush();
                      out.close();
                      fis.close();
                      
                      
          //讀取響應數據
                      int code = uc.getResponseCode();
                      String sCurrentLine 
          = "";
                      
          //存放響應結果
                      String sTotalString = "";
                      
          if (code == 200)
                      
          {
                          java.io.InputStream is 
          = uc.getInputStream();
                          BufferedReader reader 
          = new BufferedReader(
                                  
          new InputStreamReader(is));
                          
          while ((sCurrentLine = reader.readLine()) != null)
                              
          if (sCurrentLine.length() > 0)
                                  sTotalString 
          = sTotalString + sCurrentLine.trim();
                      }

                      
          else
                      
          {
                          sTotalString 
          = "遠程服務器連接失敗,錯誤代碼:" + code;
                      }

                      
          return sTotalString;
                  }

                  
          catch (Exception e)
                  
          {
                      e.printStackTrace();
                  }

                  
          return null;
              }


          服務器Servlet:
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, IOException
              
          {
                  ServletInputStream inStream 
          = request.getInputStream(); // 取HTTP請求流
                  int size = request.getContentLength(); // 取HTTP請求流長度

                  
          byte[] buffer = new byte[size]; // 用于緩存每次讀取的數據
                  byte[] result = new byte[size]; // 用于存放結果的數組
                  int count = 0;
                  
          int rbyte = 0;
                  
          // 循環讀取
                  while (count < size)
                  
          {
                      rbyte 
          = inStream.read(buffer); // 每次實際讀取長度存于rbyte中 sflj
                      for (int i = 0; i < rbyte; i++)
                      
          {
                          result[count 
          + i] = buffer[i];
                      }

                      count 
          += rbyte;
                  }


                  
          // 先找到文件名和圖片流的標志位'|'
                  int index = 0;
                  
          for (int i = 0; i < result.length; i++)
                  
          {
                      
          byte b = result[i];
                      
          if (b == '|')
                      
          {
                          index 
          = i;
                          
          break;
                      }

                  }


                  
          // 存放文件名
                  byte name[] = new byte[index + 1];
                  
          // 存放圖片字節
                  byte[] img = new byte[size - index];
                  
          for (int i = 0; i < result.length; i++)
                  
          {
                      
          if (i < index)
                      
          {
                          name[i] 
          = result[i];
                      }

                      
          if (i > index)
                      
          {
                          
          // 這時注意img數組的index要從0開始
                          img[i - index - 1= result[i];
                      }

                  }

                  
          // 還原文件名
                  String fileName = new String(name);

                  inStream.close();

                  String newFileName 
          = renameFile(fileName);
                  
          // 響應客戶端
                  response.setContentType("text/html");
                  
          // 注意響應中文數據時要設置
                  response.setCharacterEncoding("GBK");
                  PrintWriter out 
          = response.getWriter();
                  
          //可能情況 0 數據庫無相關記錄 1 文件名不符合要求 其它情況為正常
                  if(newFileName.equals("0"))
                  
          {
                      out.write(
          "0|" + fileName);
                  }

                  
          else if(newFileName.equals("1"))
                  
          {
                      out.write(
          "1|" + fileName);
                  }

                  
          else
                  
          {
                      out.write(fileName);
                  }

                  out.close();
                  
          //上傳錯誤中止后續操作
                  if(newFileName.length()<= 1)
                  
          {
                      
          return;
                  }

                  
                  File f 
          = new File(ImageSupport.getOriginal() + "/" + newFileName);
                  FileOutputStream fos 
          = new FileOutputStream(f);
                  fos.write(img);
                  fos.flush();
                  fos.close();
                  
          // 改變圖片大小后重新放置到新地點
                  ImageSupport.changeImageSize(f, ImageSupport.getAfter() + "/"
                          
          + newFileName, 300300);
              }


          我寫的是一個批量上傳圖片的程序,經測試通過.

          posted on 2009-02-06 11:54 々上善若水々 閱讀(7581) 評論(7)  編輯  收藏

          評論

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          學習 學習 你說的批量上傳是一次傳一個 傳多次,還是一次就傳多個上去。
          2009-02-06 12:41 | blackbat

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          @blackbat
          一次傳一個.不過用戶體驗到的是批量.
          2009-02-06 13:00 | 々上善若水々

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          要是在客戶端直接用java編寫程序上傳文件,直接用tcp傳二進制流就可以(當然,這要服務端也是自己實現),模擬http上傳效率有些低。
          2009-02-06 13:27 | 銀河使者

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          @銀河使者
          那樣的話是不是就像QQ一樣啊.可以直接傳送整個文件夾.對tcp接觸少.
          2009-02-06 13:50 | 々上善若水々

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          @々上善若水々
          就是傳送二進制(字節流),至于字節流里是什么,完全由用戶自己定義,當然可以是文件夾里的內容,而且都自己實現還是個好處,可以實現斷點上傳功能。甚至是多線程上傳。在服務端利用Servlet就可以實現。
          2009-02-06 14:37 | 銀河使者

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          @銀河使者
          還支持斷點?早知道就用tcp了.謝謝,有時間再嘗試一下.
          2009-02-06 15:06 | 々上善若水々

          # re: HttpURLConnection上傳文件(圖片)小試  回復  更多評論   

          @樓上
          那樣的話就搞成C/S了,客戶端服務端的代碼都得寫。
          2009-02-07 17:06 | blackbat

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 萝北县| 平果县| 思南县| 同仁县| 泰安市| 高青县| 拜泉县| 昌江| 深圳市| 竹溪县| 丽水市| 屯门区| 军事| 扎赉特旗| 长顺县| 海盐县| 香格里拉县| 边坝县| 西昌市| 衡水市| 辉南县| 阿巴嘎旗| 大邑县| 横山县| 子洲县| 万盛区| 庄浪县| 班玛县| 凭祥市| 贵阳市| 乌鲁木齐市| 同江市| 岳池县| 乌海市| 包头市| 蒲江县| 太湖县| 东兴市| 江门市| 青龙| 吉首市|