js在前端下载文件

js在前端下载文件

本文介绍了使用angular js在前端下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击文件名旁边的下载按钮时,我正在从后端获取文件内容.此内容以字节为单位.该文件可以是任何类型.如何将从后端接收的数据转换为文件,并在接收到响应(文件内容)时自动下载.HTML和Angular JS中的新蜜蜂.需要任何指针或建议:)

On click of download button beside name of a file I am getting the file content from backend . This content is in the bytes . The file can be of any type . How to convert the data received from backend to file and download it automatically on receiving response(file Content) .New bee in html and angular js .Any pointers or suggestions needed :)

推荐答案

您需要让后端告诉前端文件的位置,然后前端才能放置指向该文件的链接.后端可能应该为此文件生成一个唯一的哈希名称.

You will need to have your backend tell your front-end the location of the file, and then the front end can place a link to the file. The backend should probably generate a unique hash name for this file.

只要后端Web服务器配置了正确的mime类型,就可以将实际文件作为Rest GET请求的一部分返回.

The actual file can be returned as part of a Rest GET request as long as the backend webserver has the correct mime types configured.

因此,在您的控制器中,您将调用服务以获取文件路径:

So in your controller you would call a service to get the file path:

SomeController.$inject = ['$http'];
var SomeController = function($http) {

    var self = this;
    $http.get('/download-file-path').then(function(path) {
        self.path = path;
    }

}

然后您认为

<div ng-controller='SomeController as vm'>
    <a ng-href="{{vm.path}}">Download</a>
</div>

当角度调用 GET:/download-file-path 时,后端应返回文件的名称和路径,例如/download/file-7dje79ae.xml .然后,angular将此路径放在 a 链接中.当用户单击下载按钮时,用户浏览器将随后请求/download/file-7dje79ae.xml 并下载文件.

When angular calls GET: /download-file-path the backend should return the name and path of the file, say something like /download/file-7dje79ae.xml. Then angular puts this path in the a link. When the user clicks the download button, the users browser will then make a request to /download/file-7dje79ae.xml and download the file.

这篇关于使用angular js在前端下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 16:15