Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8738585
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T10:45:47+00:00 2026-06-13T10:45:47+00:00

I have a system in which frontend is in javascript/ajax and the backend is

  • 0

I have a system in which frontend is in javascript/ajax and the backend is written using REST(jersey).

I want to download a file using my system. I have searched various forums and implemented the REST web method as follows :

@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;

}

Initially I had used the StreamingOutput class and implemented the write method for it. In that method I had returned the string read from the file. But I have found no difference between that and the above implementation. Both return the string inside the file.

In my frontend this is what I have done

<!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>

My problem is that I am getting a file not found response( though the data variable has the content of the file), if I assign the iframe.src with the data variable

If I give the uri of the webservice (which I have given to the ajax call) to the iframe.src, I dont know how I will send the parameters.

I really need to show a download prompt to the user and allow him to save the file to the local filesystem. I dont think my REST is right either as it should show a file object in firebug during POST not the contents of the file!

I can just return the string and populate any textarea/ div with it and then ask the user to copy paste it to his file! but that does not look smooth or elegant!

Please help,
Kavita

EDIT:
Tried changing @Produces and type in Response.type() to “application/csv” as well as “application/something” but it always tries to append the contents of the file returned by the server to the current url and opens a search as file is obviously not found!!!

EDIT:
I tried converting POST to GET in the REST and used the data returned. Then it returns a DOCUMENT but still cannot open the file

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T10:45:48+00:00Added an answer on June 13, 2026 at 10:45 am

    After a lot of RnD I think I have found the solution to my problem. This might not be the ideal solution and please let me know if there are any major problems with it.

    Basically I tried accessing my file on the server and could only access it from the docroot folder (PATH = C:\glassfish3\glassfish\domains\domain1\docroot). So I realized that I must copy my file from wherever on the server to this location. I did that in the Web service. I read somewhere and was trying to send the file itself from the web service. That was wrong after this change I only sent back a plain text with the path relative to docroot.

    Then there was another setback as my file had to be within a folder and the folder name contained a # character. It seems # is not allowed and the iframe just wouldn’t ask me for the downloading!!

    Now I have modified my code as follows :
    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;
    

    My clientside code:

    <!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>
    

    Hoping someone finds it useful!!
    Thanks for the inputs!

    Kavita

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a system which contains multiple applications connected together using JMS and Spring
I have a remote embedded system which it is telnet-able. How can I download
I have a System.Data.DataTable which is populated by reading a CSV file which sets
I have a Spring MVC application which communicates with the frontend with AJAX /
We have a system with an Oracle backend to which we have access (though
I have a system which is receiving log files from different places through http
I have a system which receives leads (they are piped in via email) and
Currently we have a system which we paid for that pushes information into Excel
I need suggestion about YAMI library . I have a system which receives Json
I have to build up a system which listens for requests from a GPS

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.