我正在使用以下方法下载Web API项目中的Excel文件(在Winforms应用程序中动态创建并保存到数据库中):
[Route("api/deliveryperformance/{unit}/{begindate}/{enddate}")]
public HttpResponseMessage Get(string unit, string begindate, string enddate)
{
// adapted the first part of this code from http://stackoverflow.com/questions/11176066/how-do-i-insert-retrieve-excel-files-to-varbinarymax-column-in-sql-server-2008
byte[] excelContents;
string selectStmt = "SELECT BinaryData FROM ReportsGenerated WHERE FileBaseName = @fileBaseName";
string fbn = string.Format("deliveryperformance/{0}/{1}/{2}", unit, begindate, enddate);
using (SqlConnection connection = new SqlConnection(ProActWebReportsConstsAndUtils.CPSConnStr))
using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection))
{
cmdSelect.Parameters.Add("@fileBaseName", SqlDbType.VarChar).Value = fbn;
connection.Open();
excelContents = (byte[])cmdSelect.ExecuteScalar();
connection.Close();
}
string excelFileName = "C:\\Misc\\TestFile2.xlsx";
File.WriteAllBytes(excelFileName, excelContents);
String HtmlToDisplay = GetDownloadSuccessMessage(excelFileName);
return new HttpResponseMessage()
{
Content = new StringContent(
HtmlToDisplay,
Encoding.UTF8,
"text/html"
)
};
}
internal static string GetDownloadSuccessMessage(string excelFileName)
{
return string.Format("<h1>Excel spreadsheed downloaded to {0}</h1>", excelFileName);
}这很好(除了没有可见的下载操作,例如文件的图标下降到任务栏,就像通常从Internet下载文件时的情况一样--文件只是在指定的位置结束)。
我的假设是,这只是因为我在本地运行ASP.NET Web项目,所以我的文件系统被认为是“公平的游戏”。
我如何能够在任何远程用户的机器上完成相同的事情(最好使用前面提到的可见下载)(显然,我不能仅仅将文件放置在任何地方,这不仅是出于安全原因,而且也是因为我不知道他们可能有哪些文件夹)?
更新
我想试试这个:
HttpResponseMessage httprm = new HttpResponseMessage();
httprm.Buffer = true;
httprm.Charset = "";
httprm.Cache.SetCacheability(HttpCacheability.NoCache);
httprm.ContentType = "application/vnd.ms-excel";
httprm.AddHeader("content-disposition", "attachment;filename=\"Funk49.xlsx\"");
httprm.BinaryWrite(bytes);
httprm.Flush();
httprm.End();...adapted来自这里,但这些属性或方法都不属于HttpResponseMessage的milieau。我甚至尝试了一个原始的"Response.Buffer“代替"httprm.Buffer",希望未声明的"Response”对象(在示例代码中也没有声明)至少给我提供可解析性,但是没有这样的意外结果出现在我身上。
更新2
我将尽快赏赐被接受的答案,这是我得到过的最有用的答案之一。我将这种智慧与其他一些东西结合在一起来编译(不是双关语)--这个技巧展示了如何保存Excel数据,然后再从Web应用程序中读取出来,并下载它为这里。
发布于 2016-03-31 22:53:06
那么,您似乎没有下载任何这样的东西,只需对服务器本地C:驱动器执行一次写操作。
要下载,您需要返回excelContents缓冲区,而不是当前的HTML,例如。
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(excelContents);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "blah.xlsx";
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;https://stackoverflow.com/questions/36345052
复制相似问题