我的漫漫程序之旅

          專注于JavaWeb開發(fā)
          隨筆 - 39, 文章 - 310, 評(píng)論 - 411, 引用 - 0
          數(shù)據(jù)加載中……

          HttpURLConnection上傳文件(圖片)小試

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

          簡(jiǎn)單分析:寫入流的時(shí)候依次寫入 圖片名稱 + "|" 分隔符 +  圖片流

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

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

              
          public String upload(File f)
              
          {
                  
          try
                  
          {
                      
          //服務(wù)器IP(這里是從屬性文件中讀取出來的)
                      String hostip = FileSupport.getServerIP();
                      URL url 
          = new URL("http://"+ hostip +"/oxServer/ReceiveServlet");
                      
                      HttpURLConnection uc 
          = (HttpURLConnection) url.openConnection();
                      
          //上傳圖片的一些參數(shù)設(shè)置
                      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();
                      
                      
          //讀取響應(yīng)數(shù)據(jù)
                      int code = uc.getResponseCode();
                      String sCurrentLine 
          = "";
                      
          //存放響應(yīng)結(jié)果
                      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 
          = "遠(yuǎn)程服務(wù)器連接失敗,錯(cuò)誤代碼:" + code;
                      }

                      
          return sTotalString;
                  }

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

                  
          return null;
              }


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

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

                      count 
          += rbyte;
                  }


                  
          // 先找到文件名和圖片流的標(biāo)志位'|'
                  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];
                  
          // 存放圖片字節(jié)
                  byte[] img = new byte[size - index];
                  
          for (int i = 0; i < result.length; i++)
                  
          {
                      
          if (i < index)
                      
          {
                          name[i] 
          = result[i];
                      }

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

                  }

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

                  inStream.close();

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

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

                  
          else
                  
          {
                      out.write(fileName);
                  }

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

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


          我寫的是一個(gè)批量上傳圖片的程序,經(jīng)測(cè)試通過.

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

          評(píng)論

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

          學(xué)習(xí) 學(xué)習(xí) 你說的批量上傳是一次傳一個(gè) 傳多次,還是一次就傳多個(gè)上去。
          2009-02-06 12:41 | blackbat

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

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

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

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

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

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

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

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

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

          @銀河使者
          還支持?jǐn)帱c(diǎn)?早知道就用tcp了.謝謝,有時(shí)間再嘗試一下.
          2009-02-06 15:06 | 々上善若水々

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

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

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 凉城县| 诸城市| 同仁县| 太仆寺旗| 光泽县| 山西省| 寿光市| 景泰县| 许昌县| 工布江达县| 聂荣县| 琼中| 容城县| 神木县| 龙山县| 商城县| 利川市| 云梦县| 获嘉县| 阳原县| 同仁县| 长乐市| 清原| 平昌县| 奉化市| 平顺县| 梁平县| 芜湖县| 尼玛县| 彩票| 揭西县| 建宁县| 珠海市| 黄龙县| 涿鹿县| 龙游县| 马鞍山市| 奉化市| 郎溪县| 垦利县| 闽侯县|