从服务器下载csv文件

时间:2012-10-19 08:37:59

标签: jquery ajax rest

我有一个系统,其中前端在javascript / ajax中,后端是用REST(jersey)编写的。

我想使用我的系统下载文件。我搜索了各种论坛,并按如下方式实现了REST Web方法:

@POST
@Produces({"text/csv"})
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("getcsv")
public Response  getcsv(
        @FormParam("usernamecsv") String userid,
        @FormParam("filename") String filename
        )
{
    final File fobj = new File("c:/" +userid + "/output/" + filename);
    try
    {
        final FileInputStream f =  new FileInputStream(fobj);
ContentDisposition cd =  
        ContentDisposition.type("file").fileName(fobj.toString()).build(); 
Response response = Response
.ok()
.lastModified(new Date(fobj.lastModified()))
.type("application/octet-stream")
.header("Content-Disposition", cd)
.entity(f)
.build();
return response;
    }
    catch (FileNotFoundException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return null;

}

最初我使用了StreamingOutput类并为它实现了write方法。在那个方法中,我已经返回了从文件中读取的字符串。但我发现它与上述实现没有区别。两者都返回文件中的字符串。

在我的前端,这就是我所做的

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
function fun1()
{
$.ajax({
    url: '/RestWSGS/jersey/UserAuthentication/getcsv',
    async: false,
    data: $('#form2').serialize(),
    type: 'POST',
    cache: false,
    contentType: "application/x-www-form-urlencoded",
    processData: false,
    dataType: "text",
    success: function(data)
     {
        var iframe;
        iframe = document.getElementById("hiddenDownloader");
        if (iframe === null)
        {
            var iframe;
            iframe = document.getElementById("hiddenDownloader");
            if (iframe === null)
            {
                iframe = document.createElement('iframe');  
                iframe.id = "hiddenDownloader";
                //iframe.style.visibility = 'hidden';
                $("#mydiv").append(iframe);
            }
            iframe.src = "http:\\localhost:8080\\c:\abc@abc.com#26 8 2012 13 5 49/gr1/output/test.csv";  
//iframe.src = data; 

        }

        alert('Hi');

     }
 });
}
$(function()
        {
            $(document).delegate("#mydiv","click",function(ev)
            {
            fun1();

            });
        });

</script>
</head>
<body>
<div id="mydiv" style='position:absolute;width:20px;height:20px;background:black'></div>
<form id="form2" enctype="multipart/form-data" method="post" >
 <input id ="usernamecsv" name="usernamecsv" type="hidden"  value="abc@abc.com#26 8 2012 13 5 49/gr1"/>
  <input id ="filename" name="filename" type="hidden"  value="test.csv" />
</form>

</body>
</html>

我的问题是我收到的文件未找到响应(尽管数据变量包含文件的内容),如果我为iframe.src分配了数据变量

如果我将web服务的uri(我已经给ajax调用)给了iframe.src,我不知道如何发送参数。

我真的需要向用户显示下载提示,并允许他将文件保存到本地文件系统。我不认为我的REST是正确的,因为它应该在POST期间在firebug中显示文件对象而不是文件的内容!

我可以返回字符串并用它填充任何textarea / div,然后让用户将其复制粘贴到他的文件中!但这看起来并不光滑或优雅!

请帮忙, 卡维塔

编辑: 尝试更改@Produces并在Response.type()中键入“application / csv”以及“application / something”但它总是尝试将服务器返回的文件内容附加到当前URL并打开搜索显然找不到文件!!!

编辑: 我尝试在REST中将POST转换为GET并使用返回的数据。然后它返回一个DOCUMENT但仍然无法打开文件

2 个答案:

答案 0 :(得分:2)

您的@Produces标记与您设置的内联类型相冲突。如果你们两个都application/octet-stream,我会期待更好的结果。

答案 1 :(得分:0)

经过大量的研究后,我认为我找到了解决问题的方法。这可能不是理想的解决方案,如果有任何重大问题,请告诉我。

基本上我尝试访问服务器上的文件,只能从docroot文件夹(PATH = C:\ glassfish3 \ glassfish \ domains \ domain1 \ docroot)访问它。所以我意识到我必须将我的文件从服务器上的任何地方复制到这个位置。我在Web服务中做到了这一点。我在某处读到并试图从Web服务发送文件本身。这次更改后出错了我只回发了一条带有相对于docroot的路径的纯文本。

然后还有另一个挫折,因为我的文件必须在一个文件夹中,文件夹名称包含一个#字符。似乎#是不允许的,iframe就不会要求我下载!!

现在我修改了我的代码如下: REST:

@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("getcsv")
public String  getcsv(
        @FormParam("usernamecsv") String userid,
        @FormParam("filename") String filename
        )
{
    System.out.println("1 = " + getClass().getResource("/" +getClass().getName().substring(
            0, getClass().getName().indexOf("."))).getPath());
    System.out.println("2 = " + getClass().getResource("/" +getClass().getName().substring(
            0, getClass().getName().indexOf("."))).getPath() + "../../../../../docroot/" + userid + "/" + filename);
    final File fobj = new File("c:/" +userid + "/output/" + filename);
    try
    {
        final FileInputStream f =  new FileInputStream(fobj);
    int content;
         ByteArrayOutputStream b = new ByteArrayOutputStream();
        try
        {
            while ((content = f.read()) != -1) 
            {
                //b[j] = 0;
                // convert to byte
                b.write(content);
            }

        } catch (IOException e)
        {
            e.printStackTrace();
        } 
        finally 
        {
            try 
            {
                if (f != null)
                    f.close();
            } catch (IOException ex) 
            {
                ex.printStackTrace();
            }

        }
        File f1 =  new File( getClass().getResource("/"+getClass().getName().substring(
                0, getClass().getName().indexOf("."))).getPath() + "../../../../../docroot/" + userid.substring(0,userid.indexOf("#")) + "/" );
        f1.mkdirs();
        try
        {
        boolean f2 = new File(getClass().getResource("/" +getClass().getName().substring(
                0, getClass().getName().indexOf("."))).getPath() + "../../../../../docroot/" +  userid.substring(0,userid.indexOf("#")) + "/" + filename).createNewFile();
        System.out.println(f2);

        }
        catch (IOException e2)
        {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    FileOutputStream fout = new FileOutputStream(new File(getClass().getResource("/" +getClass().getName().substring(
            0, getClass().getName().indexOf("."))).getPath() + "../../../../../docroot/" +  userid.substring(0,userid.indexOf("#")) + "/" + filename));
    try
    {
        fout.write(b.toByteArray());
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        try
        {
            fout.close();
        }
        catch (IOException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    try
    {
        fout.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}
    catch (FileNotFoundException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return "/" +  userid.substring(0,userid.indexOf("#")) + "/" + filename;

我的客户代码:

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
function fun1()
{
$.ajax({
    url: '/RestWSGS/jersey/UserAuthentication/getcsv',
    async: false,
    data: $('#form2').serialize(),
    type: 'POST',
    cache: false,
    contentType: "application/x-www-form-urlencoded",
    processData: false,
    dataType: "text",
    success: function(data)
     {
        var iframe;
        iframe = document.getElementById("hiddenDownloader");
        if (iframe === null)
        {
            var iframe;
            iframe = document.getElementById("hiddenDownloader");
            if (iframe === null)
            {
                iframe = document.createElement('iframe');  
                iframe.id = "hiddenDownloader";
                //iframe.style.visibility = 'hidden';
                $("#mydiv").append(iframe);
            }


        }
        iframe.src = data;  
        alert('Hi');

     }
 });
}
$(function()
        {
    $(document).delegate("#hiddenDownloader","onload",function(ev)
            {
        alert('in onload');
            });

            $(document).delegate("#mydiv","click",function(ev)
            {
            fun1();

    });
        });
    </script>
</head>
<body>
<a id ='myhref'  href=""></a>
<div id="mydiv" style='position:absolute;width:20px;height:20px;background:black'></div>
<form id="form2" enctype="multipart/form-data" method="post" >
 <input id ="usernamecsv" name="usernamecsv" type="hidden"  value="abc@abc.com#26 8 2012 13 5 49/gr1"/>
  <input id ="filename" name="filename" type="hidden"  value="test.csv" />
</form>

    </body>
</html>

希望有人发现它有用!! 感谢您的投入!

卡维塔