在ASPX页面中使用c#代码从base64数据写入文件
本文关键字:base64 数据 文件 代码 ASPX | 更新日期: 2023-09-27 18:02:35
我正在尝试采用文件的base64加密版本,解密它,并将文件写入服务器。我不知道为什么这段代码不工作,任何帮助将不胜感激,因为现在我得到的错误:File Not Found
。下面是我的代码:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
public void Page_Load(object sender, EventArgs e){
HttpContext c = HttpContext.Current;
//string data = Decode(c.Request["file"]);
//string name = c.Request["name"];
string name = "target.docx";
string data = Decode("SUPER LONG BASE 64, DIDNT POST BECAUSE WAY TOO LARGE");
StreamWriter writer = File.CreateText(Server.MapPath("~/services/temp/"+name));
// Error generated here, after previous line.
writer.WriteLine(data);
writer.Close();
Response.Redirect("temp/"+name);
}
public string Decode(string str){
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
</script>
我想明白了,我需要在wwwroot上创建一个本地目录,因为在sharepoint设计器中创建的目录不是物理的,下面是代码。
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
public void Page_Load(object sender, EventArgs e){
HttpContext c = HttpContext.Current;
//string data = Decode(c.Request["file"]);
//string name = c.Request["name"];
Response.Write(Server.MapPath("/temp/hurrdurr.txt"));
string name = "target.docx";
string data = "THE GIANT BASE 64 DATA";
using(StreamWriter writer = new StreamWriter(Server.MapPath("/temp/"+name), true)){
writer.WriteLine(Decode(data));
writer.Close();
}
FileStream fs = File.Open(Server.MapPath("/temp/"+name), FileMode.Open);
byte[] file = new byte[fs.Length];
fs.Read(file, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + name);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(file);
Response.End();
}
public string Decode(string str){
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
</script>
您也可以完全避免使用临时文件。
string sName = "target.docx";
string sBase64 = "THE GIANT BASE 64 DATA";
Response.AddHeader("Content-disposition", "attachment; filename=" + sName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(System.Convert.FromBase64String(sBase64));
Response.End();