我正在尝试获取文件的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>
答案 0 :(得分:2)
我想通了,我需要从wwwroot创建一个本地目录,因为在sharepoint designer中创建的目录不是物理的,这是代码。
<%@ 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>
答案 1 :(得分:1)
您也可以完全避开临时文件。
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();