asp.net mvc将excel文件转换(编码)为base64字符串

时间:2013-06-11 20:56:15

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

我需要从我的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();
        }
到目前为止,这不能正常工作。有什么建议?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

你可以尝试:

 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;
    }
相关问题