[英]How to send a file from REST API to front-end?
I am trying to write a service which builds an.ics calendar file from string (which works) and send it to front-end.我正在尝试编写一个服务,它从字符串(有效)构建一个.ics 日历文件并将其发送到前端。 Front-end gets that file as a result of an api query.作为 api 查询的结果,前端获取该文件。 This is how it looks on my side:这就是我这边的样子:
var dataBytes = Encoding.ASCII.GetBytes(icsString);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(dataStream) };
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "file.ics" };
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponseMessage;
Is it correct?这是对的吗? If it should work, then how to get the data in JS on the front-end side?如果它应该工作,那么如何在前端获取 JS 中的数据?
Your code looks fine, you need to close the fileStream
and set responseStream
Position to 0. You can refer to my code.您的代码看起来不错,您需要关闭fileStream
并将responseStream
Position 设置为 0。您可以参考我的代码。 and please make sure that file is present at the path and you are handling the exception请确保该文件存在于路径中并且您正在处理异常
//Copy the source file stream to MemoryStream and close the file stream
MemoryStream responseStream = new MemoryStream();
Stream fileStream = System.IO.File.Open(downloadFilePath, FileMode.Open);
fileStream.CopyTo(responseStream);
fileStream.Close();
responseStream.Position = 0;
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
//Write the memory stream to HttpResponseMessage content
response.Content = new StreamContent(responseStream);
string contentDisposition = string.Concat("attachment; filename=", fileName);
response.Content.Headers.ContentDisposition =
ContentDispositionHeaderValue.Parse(contentDisposition);
return response;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.