使用httpClient上傳至遠程服務器

使用httpClient進行上傳至遠程服務器,具體代碼如下:


1、客戶端代碼,需要髮指定參數傳至服務器

/** 

 * 

 * 需要傳遞四個參數:url,remoteFilePath,fileName,localFilePathName;

 * url:http://192.168.0.125:8080/gagb/remoteFileUpload

 * remoteFilePathName:\upload\intelligence\201701\03\006301\77c39cc1-1b7e-4d57-b745-       a475cbdad256

 * localFilePathName: D:\Apache\apache-tomcat-                  6.0.45\webapps\upload\intelligence\201701\03\006301\77c39cc1-1b7e-4d57-b745-a475cbdad256

*/

 public static String submitPost(String url,String remoteFilePathName, String         localFilePathName){  

         

       HttpClient httpclient = new DefaultHttpClient();  

       

       try {  

     

           HttpPost httppost = new HttpPost(url);  


             

           FileBody bin = new FileBody(new File(localFilePathName));  

               

           //FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));   

           StringBody comment1 = new StringBody(remoteFilePathName);  

           

           //StringBody comment = new StringBody(fileName);  

 

           

           MultipartEntity reqEntity = new MultipartEntity();  

           

           // 先傳遞屬性,在傳遞文件

           reqEntity.addPart("remoteFilePath", comment1);//filename1爲請求後臺的普通參數;屬性    

           //reqEntity.addPart("fileName", comment);//filename1爲請求後臺的普通參數;屬性     

           reqEntity.addPart("file1", bin);//file1爲請求後臺的File upload;屬性     

           

           httppost.setEntity(reqEntity);

             

           HttpResponse response = httpclient.execute(httppost);

             

           int statusCode = response.getStatusLine().getStatusCode();  

             

                 

           if(statusCode == HttpStatus.SC_OK){  

                     

               System.out.println("服務器正常響應.....");  

                 

               HttpEntity resEntity = response.getEntity();  

                 

                 

               System.out.println(EntityUtils.toString(resEntity));//httpclient自帶的工具類讀取返回數據  

                 

               System.out.println(resEntity.getContent());     

 

               EntityUtils.consume(resEntity); 

               

               return "success";

               

           } else {

            return "fail";

           } 

           } catch (ParseException e) {  

               // TODO Auto-generated catch block  

               e.printStackTrace();  

               return "fail";

           } catch (IOException e) {  

               // TODO Auto-generated catch block  

               e.printStackTrace(); 

               return "fail";

           } catch (Exception e) {

            e.printStackTrace();

            return "fail";

             

           }finally {  

               try {   

                   httpclient.getConnectionManager().shutdown();   

               } catch (Exception ignore) {  

                ignore.printStackTrace();

                return "fail";

                     

               }  

           }  

       } 


2、服務器端代碼,該服務器端的代碼寫在一個servlet中;

 @Override  

 protected void doPost(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException {  

   

    System.out.println("============進入遠程上傳方法servlet==================");

        PrintWriter out = null;  

        response.setContentType("text/html;charset=UTF-8");  

        

        // 獲取遠程服務器的上下文路徑

        String contextPath = request.getSession().getServletContext().getRealPath(String.valueOf(File.separatorChar));

        File realPath1File = new File(contextPath);

String webappsPathString = realPath1File.getParent();

        Map map = new HashMap();  

        FileItemFactory factory = new DiskFileItemFactory();  

        ServletFileUpload upload = new ServletFileUpload(factory);

        File directory = null;    

        List<FileItem> items = new ArrayList<FileItem>();  

        try {  

            items = upload.parseRequest(request);  

            // 得到所有的文件  

            Iterator<FileItem> it = items.iterator();  

            while (it.hasNext()) {  

                FileItem fItem = (FileItem) it.next();  

                String fName = "";  

                Object fValue = null;  

                String fPath = null;

                if (fItem.isFormField()) { // 普通文本框的值  

                    fName = fItem.getFieldName();  

//                  fValue = fItem.getString();  

                    fValue = fItem.getString("UTF-8");  

                    map.put(fName, fValue);  

                } else { // 獲取上傳文件的值  

                    fName = fItem.getFieldName();

                    fValue = fItem.getInputStream();  

                    map.put(fName, fValue);  

                    String name = fItem.getName();  

                    if(name != null && !("".equals(name))) {  

                        name = name.substring(name.lastIndexOf(File.separator) + 1);  

                          

//                      //String stamp = StringUtils.getFormattedCurrDateNumberString();  

                        //String timestamp_Str = TimeUtils.getCurrYearYYYY();

                        //String timestamp_Str = UUID.randomUUID().toString();

                        String remoreFilePath = (String)map.get("remoteFilePath");

                        

                        String direcPath =  remoreFilePath.substring(0, remoreFilePath.indexOf(name));

                       

                        directory = new File(webappsPathString+direcPath);

                        if (!directory.exists()) {

                        directory.mkdirs();  

                        }

                          

                        //String filePath = ("e://test")+ timestamp_Str+ File.separator + name;  

                        String filePath = ("e://test")+File.separator + name;

                        

                        String allPath = webappsPathString+remoreFilePath;

                        map.put(fName + "FilePath", allPath);  

                          

                        InputStream is = fItem.getInputStream();  

                        FileOutputStream fos = new FileOutputStream(allPath);  

                        byte[] buffer = new byte[1024];  

                        while (is.read(buffer) > 0) {  

                            fos.write(buffer, 0, buffer.length);  

                        }  

                        fos.flush();  

                        fos.close();  

                        map.put(fName + "FileName", name);  

                    }  

                }  

            }  

        } catch (Exception e) {  

            System.out.println("讀取http請求屬性值出錯!");  

//          e.printStackTrace();  

        }  

          

        // 數據處理   

        try {  

            out = response.getWriter();  

            out.print("{success:true, msg:'接收成功'}");  

            out.close();  

        } catch (IOException e) {  

            e.printStackTrace();  

        }  

  

  

    }


具體可參考http://www.jb51.net/article/89757.htm


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