如何使用AngularJS从Web下载文件?

时间:2016-09-16 11:41:20

标签: angularjs web-services

我使用AngularJS从Web获取并将其存储在数据库中(我将其转换为字节数组)。 现在我想使用AngularJS下载该文件成为可能。我可以这样做吗?(我是否必须在其他地方转换字节数组?)文件扩展名可以是pdf,doc / docx,jpg。

3 个答案:

答案 0 :(得分:1)

在您成功或随后的服务中执行此操作。

var a = document.createElement('a');
a.href = 'data:here goes the mime type of file,' + encodeURI(response);
a.target = '_blank';
a.download = 'file name . extension ';
document.body.appendChild(a);
a.click();

例如:我正在从base64字符串下载csv文件

var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURI(response);
a.target = '_blank';
a.download = 'Export.csv';
document.body.appendChild(a);
a.click();

这里我是字符串base64的回复

答案 1 :(得分:1)

这是我的角度控制器

角     .module( 'viewCvForm')     .component('viewCvForm',{

    templateUrl: 'view-cv-form/view-cv-form.template.html',
    controller: ['$scope','$routeParams','Applicant',
        function ApplicantController($scope,$routeParams,Applicant) {
            console.log('Cv Controller');
            console.log($routeParams.id);

            var self=this;

            fetchCV();
            function fetchCV() {
                var applicant={
                        firstName: "",
                        lastName: "",
                        email: "",
                        phoneNumber: "",
                        jobId:0,
                        id:$routeParams.id

                }

                return Applicant.fetchCV(JSON.stringify(applicant))
                    .then(function (response) {
                        console.log(response);

                            var a = document.createElement('a');
                            a.href = 'data:application/txt,' + encodeURI(response.data);
                            a.target = '_blank';
                            a.download = 'cv.txt';
                            document.body.appendChild(a);
                            a.click();
                            d.resolve(response);
                    },
                        function (errResponse) {
                            console.error('Error while creating Interview');
                        }
                    );
            }

        }
    ]
});

response是一个Object,它有一个名为“data”的字段,其类型为byte [](在Java控制器中)。我使用此字段将文件保存到数据库中。 如何转换response.data以显示该文件中的内容,因为现在它只显示base64个字符。

答案 2 :(得分:1)

以下是在不同类型的浏览器中下载任何文件(例如:PDF)的示例代码

from datetime import datetime, date, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.gridspec as grd
from matplotlib.transforms import Bbox
from matplotlib.finance import candlestick_ohlc, volume_overlay3, volume_overlay
#from matplotlib.finance import candlestick
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY, HourLocator, MinuteLocator


import numpy as np
import pandas as pd


def plot_underlying_hft_data(filename):


    #Read the data and filtered out the required rows and columns
    print("Reading File.. ", filename)
    tempdata = pd.read_csv(filename, index_col = ['Date'])
    tempdata = tempdata.loc[(tempdata.index == '2016-09-16')]

    tempdata['Datetime'] =  pd.to_datetime(tempdata['Datetime'], format='%Y-%m-%d %H:%M:%S')
    print(tempdata)

    HourLocator

    hour = HourLocator()    
    minute = MinuteLocator()
    hourformatter = DateFormatter('%H:%M') 

    #tempdata['Datetime'] = tempdata['Datetime'].apply(lambda datetimevar : datetime)

    tempdata['DatetimeNum'] = mdates.date2num(tempdata['Datetime'].dt.to_pydatetime())

    quotes = [tuple(x) for x in tempdata[['DatetimeNum', 'Open', 'High', 'Low', 'Close', 'Volume']].to_records(index=False)]

    #print(quotes)    
    title_name_ohlc = 'OHLC Intraday Chart'
    #print(title_name_ohlc)
    plt.figure(figsize = (12,6))
    #plt.title(title_name_ohlc)
    ax1 = plt.subplot2grid((1,1), (0,0), axisbg='w')

    ax1.set_ylabel('Price', fontsize=12, fontweight = 'bold')
    ax1.set_title(title_name_ohlc, fontsize=14, fontweight = 'bold')
    ax1.set_ylabel('Price', fontsize=12, fontweight = 'bold')
    ax1.set_title(title_name_ohlc, fontsize=14, fontweight = 'bold')
    print(tempdata['DatetimeNum'].min(), tempdata['DatetimeNum'].max())
    ax1.set_ylim(bottom = tempdata['DatetimeNum'].min(), top = tempdata['DatetimeNum'].max())

    ax1.xaxis.set_major_locator(hour)
    ax1.xaxis.set_minor_locator(minute)
    ax1.xaxis.set_major_formatter(hourformatter)
    #ax1.grid(True)
    candlestick_ohlc(ax1, quotes, width=1, colorup='g', colordown='r', alpha = 1.0)
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.show()

plot_underlying_hft_data("data.csv")

        #print(tempdata.head(5))