zoukankan      html  css  js  c++  java
  • mvc api 下载文件问题

    背景:前后端分离项目,文件下载

    项目中 因为实际文件名和路径里的文件名 不一致(一般路径文件名需要使用唯一名字)

    刚开始使用返回链接的方式,会出现图片直接预览,文件名会以路径文件名下载,用户体验不好。

    更改方案:1、js 有方法以特定的名字下载,但是有跨域问题。

         2、使用api 下载文件。

        主要是api 下载文件遇到的问题,

                刚开始使用一下代码方式,在本地开发环境可以下载,到了测试服务器上就下载不了。

    path = path.Replace(WebSiteDisc, "");
    path = path.Replace("/Upload", "").Replace("/", "\");
    string filePath = WebSiteDisc + path;
    logger.Info(filePath);
    if (File.Exists(filePath))
    {
    FileInfo fi = new FileInfo(filePath);

    // StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
    logger.Info("长度:" + fs.Length);
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ClearHeaders();
    response.ClearContent();
    response.Buffer = true;
    // response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fi.Name));
    response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlDecode(filename, System.Text.Encoding.UTF8));
    response.AddHeader("Content-Length", fi.Length.ToString());
    response.AddHeader("Content-Transfer-Encoding", "binary");

    response.ContentEncoding = Encoding.GetEncoding("GB2312");
    response.Charset = "gb2312";
    response.ContentType = "application/octet-stream";
    response.WriteFile(filePath);
    logger.Info("下载完成" + filePath);
    response.Flush();
    response.Close();

    }

    后续更改文件下载方式,

    添加了一行打开文件的代码

    FileStream str = File.OpenRead(filePath);   测试服务器也可以正常下载了,但是会有多个进程占用问题

    再次把代码改为       FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

    读写共享的方式,可以正常下载了,当然还有一个要注意的问题就是 中文编码下载的问题,

    加了一些编码控制,chrome 和firox 都可以了,ie还是有一些问题,最好不得已用实际的id作为文件名下载了(大家帮忙提供意见)。

  • 相关阅读:
    Azure PowerShell (2) 修改Azure订阅名称
    Windows Azure Platform Introduction (11) 了解Org ID、Windows Azure订阅、账户
    Azure PowerShell (3) 上传证书
    Azure PowerShell (1) PowerShell入门
    Windows Azure Service Bus (2) 队列(Queue)入门
    Windows Azure Service Bus (1) 基础
    Windows Azure Cloud Service (10) Role的生命周期
    Windows Azure Cloud Service (36) 在Azure Cloud Service配置SSL证书
    Android studio 使用心得(一)—android studio快速掌握快捷键
    android 签名、混淆打包
  • 原文地址:https://www.cnblogs.com/jayblog/p/13219685.html
Copyright © 2011-2022 走看看