如何以与在我的机器上下载文件的方式相同或类似的方式将文件下载到远程机器上?
如何以与在我的机器上下载文件的方式相同或类似的方式将文件下载到远程机器上?
我正在使用以下方法在Web API项目中下载一个Excel文件(在Winforms应用程序中动态创建并保存到数据库中):
[Route("api/deliveryperformance/{unit}/{begindate}/{enddate}")] public HttpResponseMessage Get(string unit, string begindate, string enddate) { 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("Excel spreadsheed downloaded to {0}
", excelFileName); }
这个方法运行良好(除了没有显示下载操作,比如文件的图标掉到任务栏,通常在从互联网下载文件时会出现 - 文件只会出现在指定的位置)。
我的假设是这只在本地运行ASP.NET Web API项目时才有效,所以我的文件系统被认为是“公平游戏”,可以进行写操作。
如何在任何远程用户的机器上实现相同的事情(最好是具有以前提到的可见下载)(显然,我不能随意将文件放在任何地方,不仅因为安全原因,还因为我不知道他们可能有哪些文件夹)?
更新:
我打算尝试这样做:
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();
...从这里改编而来,但是HttpResponseMessage的属性和方法中的那些属性和方法都不是它的一部分。我甚至尝试了用原始的“Response.Buffer”来代替“httprm.Buffer”,希望未声明的“Response”对象(在示例代码中也没有声明)能够至少给我一个可解析的结果,但是没有这样的好运降临在我身上。
更新2:
我会尽快奖励接受的答案;这是我收到过的最有用的答案之一。我将这个智慧与其他点滴结合起来,编写了一个提示,展示了如何从Web API应用程序中保存Excel数据,然后再次读取并下载它,在这里可以找到:here。
这个问题的出现原因是用户想要了解如何将文件下载到远程机器,与下载到自己的机器相同或类似的方式。解决方法是通过返回文件的字节流来实现下载,而不是返回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;
这段代码将下载的文件内容存储在`excelContents`变量中,然后将其作为字节流返回给客户端。通过设置响应消息的`ContentDisposition`和`ContentType`头信息,将文件保存为附件,并指定文件名和内容类型为`application/octet-stream`。
这种方法可以完美地下载Excel文件,而不仅仅是HTML字符串。用户表示这正是他所需要的解决方案。