简体   繁体   English

Ajax请求通过发布请求获取文件

[英]Ajax request get file through post request

I have a Ajax post request which might receive static file in response, but i don't know how to show that file to the client.i mean something like download function through post request. 我有一个Ajax发布请求,该请求可能会收到静态文件作为响应,但是我不知道如何向客户端显示该文件。我的意思是通过发布请求下载功能。

here is my sample ajax request: 这是我的示例ajax请求:

function Getfile(id)
                {
                var mhost='http://myhost/post';
                $.ajax({
                  type: 'POST',
                  url: mhost,
                  data: { task: 'getfile', id: myid },
                  beforeSend:function(){
                    // this is where we append a loading image

                  },
                  success:function(data){
                    // successful request; how to show file to the user for download?
                  },
                  error:function(){
                    // failed request; give feedback to user

                  }
                });

                }

thanks in advance 提前致谢

One way is to treat them both as any other html and show it in the browser; 一种方法是将它们与其他任何html一样对待,并在浏览器中显示出来。

success:function(data){
    // successful request; how to show file to the user for download?                  },
    location.href = data;

For PDF, users who has a PDF viewer will likely see it straight and users who don't will get a download request. 对于PDF,具有PDF查看器的用户可能会直接看到它,而没有PDF查看器的用户将收到下载请求。

For TXT, most user will likely see it straight and the rest will get a download request. 对于TXT,大多数用户可能会直接看到它,其余用户将获得下载请求。

The action taken by their browser depends on the browser settings. 他们的浏览器采取的操作取决于浏览器设置。

You can do it in another way though, using content-headers. 但是,您可以使用内容标题以另一种方式进行操作。 This link has more info about that: How do I force download with HTML/JavaScript? 该链接具有有关此的更多信息: 如何强制使用HTML / JavaScript下载?

This also means that you force something else on the user, that they might not like. 这也意味着您向用户强加了其他用户可能不喜欢的东西。

A third approach could be offering them a choice, whether to download or read it online. 第三种方法是为他们提供选择,是在线下载还是阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM