我正试图在我的电脑上向我的客户端发送一个文件。我环顾四周,大多数答案如下:如何在ASP.NET WebAPI 中返回文件(FileContentResult(
所以我试着自己实现它,但我只收到了标题。我一定认为我做错了什么,但我不知道在哪里。我在区分c版本时有点困难,但它应该工作的目标是.Net 4.8。
我发送文件的代码:
[HttpGet("ftplog")]
public HttpResponseMessage Get()
{
String fileName = "FileZilla Server.log";
String path = @"C:UsersjacqqsourcerepostestingtestingViewsHomeFileZilla Server.log";
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var memoeryStream = new MemoryStream();
fileStream.CopyTo(memoeryStream);
memoeryStream.Seek(0, SeekOrigin.Begin);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(memoeryStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName.ToString()
};
return result;
}
我尝试过发送FileStream而不是MemoryStream,我也尝试过将文件作为ByteArrayContent发送,但我总是只接收标头。我已经检查过了,文件中的数据读取正确。可能是我的接收代码错了?
public static async Task DownloadFileTaskAsync(HttpClient client, Uri uri, string FileName)
{
var s = await client.GetStreamAsync(uri);
StreamReader reader = new StreamReader(s) ;
Console.WriteLine("Starting");
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("stopping");
}
我是c#的新手,所以可能是我忽略了什么。如果有人知道发送文件的不同/更好的方式,我也很想听听。以下是我收到的:
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["application/octet-stream"]},{"key":"Content-Disposition","value":["attachment; filename="FileZilla Server.log""]}]},"statusCode":100,"reasonPhrase":"Continue","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":false}
请帮忙,被困的时间有点太长了。
[HttpGet("ftplog")]
public FileStreamResult Get()
{
string fileName = "FileZilla Server.log";
string path = @"C:UsersjacqqsourcerepostestingtestingViewsHomeFileZilla Server.log";
var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
var memoryStream = new MemoryStream();
fileStream.SaveAs(memoryStream);
memoryStream.Position = 0;
return new FileStreamResult(memoryStream, "application/octet-stream")
{
FileDownloadName = $"{fileName}.log"
};
}