下载文件名不起作用的属性?

时间:2015-11-25 06:24:14

标签: html html5 href

下载属性用于使浏览器下载锚点指向的资源,而不是导航到它。作为选项,可以提供下载文件的新文件名。

请注意,并非所有浏览器都支持此功能。见http://caniuse.com/#feat=download

我们假设我们有以下锚链接:

<a href="http://video-js.zencoder.com/oceans-clip.mp4" download="video.mp4"> download </a>

点击链接,我希望下载名为video.mp4的文件。但实际的文件名是oceans-clip.mp4,用于下载的文件。你知道为什么这里没有使用新的文件名吗? (我用Chrome测试过这个)

谢谢!

2 个答案:

答案 0 :(得分:27)

根据HTML element reference->[a]

  

可与blob:URL和数据:URL一起使用,以方便用户下载使用JavaScript以编程方式生成的内容(例如使用在线绘图Web应用程序创建的图片)。

     

如果HTTP标头Content-Disposition:存在且提供的文件名与此属性不同,则HTTP标头优先于此属性。

     

如果此属性存在且Content-Disposition:设置为内联,则Firefox优先考虑Content-Disposition,例如文件名大小写,而Chrome优先考虑下载属性。

     

此属性仅适用于具有相同来源的资源的链接。

它不是来自同一个来源,因此它不起作用。

答案 1 :(得分:12)

这实际上可以通过JavaScript实现,但浏览器支持会有点不稳定。您可以使用XHR2将文件作为Blob从服务器下载到浏览器,创建Blob的URL,使用其href属性创建锚并将其设置为该URL,将download属性设置为您希望它的任何文件名是,然后单击链接。这适用于Google Chrome,但我尚未在其他浏览器中验证支持。

using ChattingInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ChatClient
{
    /// <summary>
    /// Interaction logic for ChatWPFClient.xaml
    /// </summary>
    public partial class ChatWPFClient : Window
    {
        public static IChattingService Server;
        private static DuplexChannelFactory<IChattingService> _channelFactory;
        public ChatWPFClient()
        {
            InitializeComponent();
            _channelFactory = new DuplexChannelFactory<IChattingService>(new ClientCallback(), "ChattingServiceEndpoint");
            Server = _channelFactory.CreateChannel();

        }

        private void sendMessage(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Not available yet!");
        }

        public void TakeMessage(string message, string userName)
        {
            chatBox.Text += userName + ": " + message + "\n";
        }
    }
}