【问题标题】:asp.net mvc convert(encode) excel file to base64 stringasp.net mvc convert(encode) excel文件到base64字符串
【发布时间】:2013-06-11 20:56:14
【问题描述】:

我需要从我的 asp.net mvc 项目文件夹中提取一个 excel 文件并将其编码为 base64 字符串。

现在我的代码:

 string base64 = String.Empty;
 var pathName = Server.MapPath("~/App_Data/ImportTemplate.xlsx");`
 byte[] docBytes = null;

using (StreamReader strm = new StreamReader(pathName, System.Text.Encoding.UTF8))
        {
            Stream s = strm.BaseStream;
            BinaryReader r = new BinaryReader(s);
            docBytes = r.ReadBytes(Convert.ToInt32(r.BaseStream.Length));
            base64 = Convert.ToBase64String(docBytes);
            r.Close();
            s.Close();
            strm.Close();
        }

到目前为止,这还不能正常工作。有什么建议么?

【问题讨论】:

  • 到底有什么问题?它会抛出异常吗?
  • 我的 web 服务拒绝/拒绝它,然后我将该 base64 字符串再次转换为 byte[] 并传递给方法。
  • 您可以发布错误详细信息吗? “我的网络服务拒绝/拒绝它”是什么意思
  • 点击查看详情,可能你的要求太大了。
  • 查看File.ReadAllBytes(pathName)msdn.microsoft.com/en-us/library/…

标签: c# asp.net asp.net-mvc asp.net-mvc-4 encoding


【解决方案1】:

问题很可能是您的 base64 数据包含“+”和“/”字符,这些字符由 HTTP 专门解释。您需要将该二进制文件转换为他们所谓的 base64 URL 编码,该编码对这些字符使用“-”和“_”。 http://api.adform.com/Services/Documentation/Samples/MediaPlanServiceSamples.htm#ImportMediaPlan 的示例表明情况就是这样。

有关如何进行转换的信息,请参阅https://stackoverflow.com/a/17032614/56778

【讨论】:

    【解决方案2】:

    你可以试试:

     byte[] docBytes = ReadFile(pathName);
    
    
     byte[] ReadFile(string sourcePath)
        {
            byte[] data = null;
            FileInfo fileInfo = new FileInfo(sourcePath);
            long numBytes = fileInfo .Length;
            FileStream fileStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fileStream);
            data = br.ReadBytes((int)numBytes);
            fileStream .Close();
            return data;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2015-01-28
      相关资源
      最近更新 更多