2011-11-25 92 views
1

我在我的html中有一個input type = file標記,允許用戶選擇多個文件。該窗體的動作是一個REST Web服務:使用REST上傳多個文件

@POST 
@Path("savefile") 
@Produces ({MediaType.TEXT_PLAIN}) 
public String createObjects(
     @FormDataParam("datafile") FormDataMultiPart file, 
     @FormParam("username") String unm 
     //@Context HttpServletRequest request 
     ){....} 

起初,我使用的請求對象檢索請求中的所有FileItems,然後將其保存到服務器。沒有問題。現在我想發送一個字符串數據和文件。爲此我讀了參數需要是FormDataParam類型。因此我添加了該參數。這是我的客戶端代碼:我不知道什麼必須是文件參數的類型,允許在它的多個文件

<form id="form1" action="http://comp1:8080/RestWSGS/jersey/UploadFiles/savefile" 
     enctype="multipart/form-data" method="post"> 
     <input name="username" type="text" style="display:none" value="abc"/> 
    <input id="loadId" multiple="multiple" 
     type="file" name="datafile" required="required" autofocus="autofocus" 
     onchange="selectFiles(this)"/> 
    <div> 
    <input style="display: none;" type="submit" value="Send"> 
    </div> 
</form> 

???? 文件參數給我多個文件,或者我必須恢復到@Context注入?如果是這樣,我將如何檢索字符串參數?

歡迎任何幫助!

編輯: 我已經修改了我的休息WS以下幾點:

@POST 
@Path("savefile") 
//@Consumes (MediaType.MULTIPART_FORM_DATA) 
public void createObjects(
     //@FormDataParam("datafile") FormDataMultiPart file, 
     //@FormParam("username") String unm 
     @Context HttpServletRequest request 
     ) 
{ 
    try 
    { 
     FileHandler f; 
     f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(
       0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") + "/mylog.log"); 
     logger.addHandler(f); 

    } 
    catch (SecurityException e1) 
    { 
     logger.info(e1.getMessage()); 

    } 
    catch (IOException e1) 
    { 
     logger.info(e1.getMessage()); 
     //e1.printStackTrace(); 
    } 


    ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(
      0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") ; 
    ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring 
    (0, ApplicationConstants.ROOTPATH.indexOf("\\") + 2); 
    String user = request.getParameter("username"); 
    logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH); 


    try 
    { 
     for (Part part : request.getParts()) 
     { 
       try 
       { 
        logger.info("part = " + part.getName()); 
        if (!part.getName().equalsIgnoreCase("username")) 
        { 
         String fileName = processFileName(part.getName()); 
         part.write(new File(ApplicationConstants.ROOTPATH + user + "\\" + fileName).getPath()); 
        } 

        else 
        { 
         user = request.getParameter("username"); 
         logger.info("user = " + user); 
        } 
       } 
       catch (IOException e) 
       { 
        logger.info(e.getMessage()); 

       } 
     } 
    } 
    catch (IOException e) 
    { 

    } 
    catch (ServletException e) 
    { 

    } 
} 

但我總是正從用request.getParameter爲空值(「用戶名」)。我不知道什麼是錯的!以多部分/形式 - 數據形式發送其他數據是否違法?我需要一些指針。請在此代碼中提出任何改進建議。

+0

您可以通過相關的編程語言 – JohnP

+0

一個標記它爲你的問題更好的可視性非常好的例子(客戶端和服務器端代碼)上傳多個文件通過RESTful Web服務是 - HTTP://crispcode.wordpress .com/2012/07/27/jersey-rest-web-service-to-upload-multiple-files /其他相關主題是 - http://crispcode.wordpress.com/2012/07/10/jersey-rest- Web服務對上載的文件/ – Chetan

回答

3

以下是適合我的解決方案。可以使用零件中的輸入流來訪問多部分/ formdata請求情況下的請求部分。我想發送一個字符串和一些文件到我的REST網絡服務。我發現了一個ServletFileUpload/FIleItem示例發佈在幾個網站上,但我無法檢索字符串(我認爲如果所有數據都不是文件類型)。因此,我修改了我的web服務以下,而不是我可以做一個字符串和一些文件的處理:

private static Logger logger = Logger.getLogger("UploadFiles"); 
@POST 
@Path("savefile") 
public void createObjects(@Context HttpServletRequest request) 
{ 
    try 
    { 
     FileHandler f; 
     f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(
       0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") + "/mylog.log"); 
     logger.addHandler(f); 

    } 
    catch (SecurityException e1) 
    { 
     logger.info(e1.getMessage()); 

    } 
    catch (IOException e1) 
    { 
     logger.info(e1.getMessage()); 
    } 
    ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(
      0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") ; 
    ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring 
    (0, ApplicationConstants.ROOTPATH.indexOf("\\") + 2); 
    String user = request.getParameter("username"); 
    logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH); 
    logger.info("username" + user); 
    try 
       { 
     for (Part part : request.getParts()) 
     { 

        logger.info("part = " + part.getName()); 
        if (!part.getName().equalsIgnoreCase("username")) 
        { 
         try { 
         BufferedInputStream in = new BufferedInputStream(part.getInputStream()); 
         String filename = getFilename(part); 
         boolean success = (new File(ApplicationConstants.ROOTPATH + user + "\\")).mkdir(); 
         if (success) { 
         System.out.println("Directory: " + ApplicationConstants.ROOTPATH + user .trim()+ "\\" + " created"); 
         } 
         else 
         { 
          System.out.println("not created"); 
         } 
         FileOutputStream out = new FileOutputStream(ApplicationConstants.ROOTPATH + user + "\\" + filename); 

         byte[] data = new byte[1000]; 
         int bytesRead = 0; 
         int offset = 0; 
         while (offset < part.getSize()) 
         { 
          bytesRead = in.read(data); 
          if (bytesRead == -1) 
          { 
           break; 
          } 
          offset += bytesRead; 
          out.write(data); 
         } 

         in.close(); 

         if (offset != part.getSize()) 
         { 
          throw new IOException("Only read " + offset + " bytes; Expected " + part.getSize() + " bytes"); 
         } 
         out.flush(); 
         out.close(); 
         } 
         catch (Exception e) 
         { 
          logger.info(e.getMessage()); 
         } 
        } 
        else 
        { 
         BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8")); 
         StringBuilder value = new StringBuilder(); 
         char[] buffer = new char[1024]; 
         reader.read(buffer); 
         value.append(buffer); 
         user = value.toString().trim(); 
         logger.info("user = " + value); 
        } 

} 
    } 
    catch (IOException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch (ServletException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

希望這可以幫助別人!