如何使用Java脚本ajax调用下载TXT文件

how to download txt file with using java script ajax call

本文关键字:下载 TXT 文件 调用 ajax 何使用 Java 脚本      更新时间:2023-09-26

我想下载一个文本文件(例如:- something .txt)。当我使用ancor标记时,文件被下载,但我想使用ajax调用下载文件。

HTML代码:
<body>
    <a href="#" id="exportViewRule">Export</a>
</body>

JavaScript代码:

$("#exportViewRule").click(function(){
            $.ajax({
                url : "/download/myDir/exportFile",
                type : "GET",
                contentType : "text/plain",             
                success : function(data){
                    alert(data);
                }
        });
    });
java代码:

@Path("/myDir")
public class IdnsDataHandler {
@GET
    @Path("/exportFile")
    @Produces("text/plain")
    public Response exportFile(){
        File file=new File("/home/cerdik/Desktop/some.text");
        ResponseBuilder response=Response.ok((Object)file);
        response.header("Content-Disposition","attachment; filename=export-file.text");
        return response.build();
    }
}

当我使用下面的代码(没有javascript),下载工作。

HTML代码:

<body>
    <a href="./download/myDir/exportFile" id="exportViewRule">Export</a>
</body>

感谢大家,我找到了另一个解决方案,这种类型的下载方法,现在我没有使用ajax调用,下面显示到我的成功代码

Html:

<a id="exportView" style="cursor:pointer">Export</a>
javaScript:

$("#exportView").click(function(){
            var exportId = $('#serviceRules option:selected').attr("stream");
            var TakeHref="./download/myDir/exportFile"+exportId;
            document.getElementById("exportView").setAttribute("href", TakeHref);
        });

此代码在我的应用程序中成功运行,谢谢大家。

我认为你必须在url后面加上文件的结尾(例如。txt)

$.ajax({
   url : "/download/myDir/exportFile.txt",
   ...
})

您应该使用ajax调用,诀窍是定义dataType然后响应将是.txt文件所包含的内容。

$.ajax({
        url : "some-file.txt",
        dataType: "text",
        success : function (data) {
            // set text to preferred DOM
            $("THE-DOM").html(data);
        }
    });

答案是:没有你不能

AJAX请求在浏览器中呈现的页面中完成。它们请求存储在XMLHTTPObject中的文件的内容。content-type的响应头没有区别,会被浏览器忽略。

更准确地说:

AJAX调用在响应头设置为TEXT/HTML的页面内执行,这意味着文件的内容是由AJAX请求的。响应头不会被调用重置,因此不会触发下载。

当单击链接时,描述文件内容的响应头由JAVA代码发送到页面,从而产生一个响应,该响应被浏览器视为下载。

如果你真的需要JS干预来改变你的参数,这段代码片段应该做的就是。但这不是一个好方法。

//your JS function to manipulate the url
function downloadFile(){
  var url = "/download/myDir/exportFile";//+your extra params
  $('#fake').prop({'src':url});
}
<a href="#" onclick="downloadFile()" id="exportViewRule">Export</a>
<iframe name="fake" id="fake" style="display:none;"></iframe>