从Rest服务接收excel文件作为javascript中的响应 [英] receive an excel file as response in javascript from a Rest service

查看:26
本文介绍了从Rest服务接收excel文件作为javascript中的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从javascript调用网络服务,以获取Excel文件作为来自服务器的Java appl的响应.我有点困惑如何获取响应并进行访问.在Web服务代码中-我从列表中获取数据(大量数据超过90000条记录),并将其写入excel工作表,然后将excel文件作为响应发送(我不确定代码是否正确-我对其进行了测试而且没有例外,但不确定逻辑),然后如果响应为null抛出错误,并且我的问题在这里,则Javascript代码SubmitReport方法将调用Rest Web服务.我不知道如何从响应中读取/下载数据.请给我一些建议或示例代码以实现我的目标.

I am calling a webservice call from javascript to get an excel file as response from java appl from server. I am kind of stuck how to get the response and access it. Here in the webservice code- I am getting data from a list(lots of data more than 90000 records) and writing it to an excel sheet and sending the excel file as response(I am not sure whether the code is right-I tested it and no exceptions but not sure on logic) and then the Javascript code- submitReport method calls the Rest webservice-if response is null throw error and the problem for me is here. I dont know how to read/download data from the response. Please give me some suggestions or sample code to achieve my goal.

网络服务代码:

  @POST   
    @Path("/report")   
    @Consumes(MediaType.MULTIPART_FORM_DATA)   
    @Produces("application/vnd.ms-excel")   
    public Response getReportData(@Context HttpServletRequest request,   
      @FormDataParam("fromTimeStamp") String fromTimeStamp, @FormDataParam("toTimeStamp") String toTimeStamp) {      
    EOServiceResult<List<TagDataPoint>> result = new EOServiceResult<List<TagDataPoint>>();    
    List<TagDataPoint> listTotalResult = repo.getReportData(fromTimeStamp, toTimeStamp);//This method returns lots of data more than 90000 records.   
    //Blank workbook   
     final XSSFWorkbook workbook = new XSSFWorkbook();    
          //Create a blank sheet   
           final XSSFSheet sheet = workbook.createSheet("Report");   
     //This data needs to be written (Object[])    
            Map<Integer, Object[]> data = new TreeMap<Integer, Object[]>();    
            data.put(1, new Object[] {"Historian Tag", "Quality", "Value", "Timestamp"});  
            int i = 2;   
            for(TagDataPoint tagData : listTotalResult){   
                data.put(i, new Object[] {tagData.getTagname(), tagData.getQuality(), tagData.getValue(), tagData.getTimestamp()});   
                 i++;   
            }  
         //Iterate over data and write to sheet   
            Set<Integer> keyset = data.keySet();   
        int rownum = 0;
            for (Integer key : keyset)   
        {   
            Row row = sheet.createRow(rownum++);    
            Object [] objArr = data.get(key);   
            int cellnum = 0;   
            for (Object obj : objArr)    
            {    
               Cell cell = row.createCell(cellnum++);   
               if(obj instanceof String)    
                    cell.setCellValue((String)obj);    
                else if(obj instanceof Integer)   
                    cell.setCellValue((Integer)obj);   
                else if(obj instanceof Date)    
                    cell.setCellValue((Date)obj);    
            }   
        }    
        ResponseBuilder response = null;   
        try{    
        File file = new File("first_excel.xlsx");     
        FileOutputStream out = new FileOutputStream(file);     
        workbook.write(out);    
        out.close();    
        response = Response.ok((Object) file);    
        }catch(Exception e){    
            e.printStackTrace();   
        }    
       //  ResponseBuilder     
     response.header("Content-Disposition", "attachment; filename=\"test_excel_file.xls\"");      
        return response.build();      
        }    
    **Javascript code:**      
     databaseFactory..getReportResponse: function( fromTimeStamp, toTimeStamp ){   
        var blankFormData =  new FormData();   
          blankFormData.append("fromTimeStamp", fromTimeStamp);   
          blankFormData.append("toTimeStamp", toTimeStamp);   
          var promise = $http(   
             {   
                "method":"POST",    
                "url":SERVER+'/EfficiencyMap/api/v1/datamodel/report' ,    
                "data":blankFormData,   
                "timeout":100000,   
                headers: { 'Content-Type' :  undefined},    
                transformRequest : angular.identity   
             })    
             .success(function(response){   
                return response;   
             });   
          return promise;  
           }   
    **//Actual method after the response**     
    $scope.submitReport = function(fromTimeStamp, toTimeStamp){     
       databaseFactory.getReportResponse(fromTimeStamp,     toTimeStamp).success(function(response){   
            if(response == null){    
               $scope.message = DATA_NOT_AVAILABLE + fromTimeStamp +  " and " + toTimeStamp;   
                return;   
            }  
     **// So what should be done here any suggestions please    
            // I don't understand the response here. How should I download the file here**          
    };    

我需要在前端自动下载响应excel文件.这是我编写的第一个Web服务请求/响应调用.因此,请提供有关如何从服务器读取响应的帮助.

推荐答案

在JAX-RS中,对于excel文件,请使用@Produces("application/vnd.ms-excel")注释该方法:

In JAX-RS, for excel file, annotate the method with @Produces("application/vnd.ms-excel") :

1.在服务方法上输入@Produces("application/vnd.ms-excel").

1.Put @Produces("application/vnd.ms-excel") on service method.

2.在Response标头中设置"Content-Disposition"以提示下载框.

2.Set "Content-Disposition" in Response header to prompt a download box.

代码:

import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("/excel")
public class ExcelService {

    private static final String FILE_PATH = "c:\\excel-file.xls";

    @GET
    @Path("/get")
    @Produces("application/vnd.ms-excel")
    public Response getFile() {

        File file = new File(FILE_PATH);

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition",
            "attachment; filename=new-excel-file.xls");
        return response.build();

    }

}

我不知道它是否仍然有用,但是您可以看到

I do not know if it is still useful, however you can see

这篇关于从Rest服务接收excel文件作为javascript中的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆