1. 程式人生 > >jersey上傳下載檔案及客戶端呼叫程式碼

jersey上傳下載檔案及客戶端呼叫程式碼

基礎環境就不說了, 直接上程式碼:
服務方程式碼:

//上轉
@POST
    @Path("Upload")
    public String postBytes( final byte[] by,@QueryParam("filename") final String  filename) {//上轉,不能再加其他的欄位
        try {
            FileUtil.transformToFile(by, "D:\\"+filename+"");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return
"ok"; }
//下載
@POST
    @Path("download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)//返回方式為流  
    public  byte[] postFile(@FormParam("filename") final String  filename) throws Exception { //讀出檔案,返回檔案流,下載
        String filepath = "D:\\"+filename+"";
        File file = new File(filepath);
        return
FileUtil.transformToByte(file); }

客戶端呼叫的話配置連線的一部分就省略了:
這是呼叫的程式碼:

//建立連線,之後傳送流檔案,和檔名,服務端來接收
   public  void Upload() throws Exception {
        final WebTarget webTarget = client.target(Jaxrs2Client.BASE_URI);
        final WebTarget pathTarget = webTarget.path("in-resource").path("Upload").queryParam
("filename", "你好HQGT-WS.zip");//傳送的檔名 String filepath = "D:\\HQGT-WS.zip";//真實路徑 File file = new File(filepath); byte[] bb= FileUtil.transformToByte(file); Jaxrs2Client.LOGGER.debug(pathTarget.getUri()); final String rest = pathTarget.request().post(Entity.entity(bb, MediaType.APPLICATION_FORM_URLENCODED_TYPE),String.class); Jaxrs2Client.LOGGER.debug(rest); System.out.println(rest); }
//下載程式碼
//傳入需要下載檔名或標識一類的,返回位元組流,轉換成檔案
 public  byte[]  download() throws Exception {
         final WebTarget webTarget = client.target(Jaxrs2Client.BASE_URI);
         final WebTarget pathTarget = webTarget.path("in-resource").path("download");
         final Form form = new Form();
         form.param("filename", "HQGT-WS.zip");//要下載下來的檔名
         Jaxrs2Client.LOGGER.debug(pathTarget.getUri());
         final byte[] invocationBuilder = pathTarget.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), byte[].class);
         Jaxrs2Client.LOGGER.debug(invocationBuilder);
         return invocationBuilder;
    }

有問題可在下面留言。