[英]How can I download file in my folder c# ASP.NET Web API?
I need a download file in my C:\fileName
.我的
C:\fileName
中需要一个下载文件。
I am send to fileName this class but it does not working?我被发送到 fileName 此类,但它不起作用? Where is my error?
我的错误在哪里?
This is my code:这是我的代码:
// POST: api/Calendar/DownloadFile
[HttpPost]
public HttpResponseMessage DownloadFile(DownloadInput fileName)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
var filePath = HttpContext.Current.Server.MapPath(@"C:\" + fileName);
var fileBytes = File.ReadAllBytes(filePath);
var fileMemStream = new MemoryStream(fileBytes);
result.Content = new StreamContent(fileMemStream);
var headers = result.Content.Headers;
headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
headers.ContentDisposition.FileName = fileName;
headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
headers.ContentLength = fileMemStream.Length;
return result;
}
This is my error:这是我的错误:
ExceptionType: "System.NotImplementedException"
异常类型:“System.NotImplementedException”
Message: "An error has occurred."消息:“发生错误。”
The below is for MVC:以下是 MVC 的:
public ActionResult DownloadFile(string fileWithFullPath)
{
var fileBytes = System.IO.File.ReadAllBytes(fileWithFullPath);
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
The below is for API:以下是API:
public ActionResult DownloadFile()
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(fullyQualifiedFileName, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentLength = stream.Length;
string input = $"filename=test.pdf";
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse(input, out contentDisposition))
{
result.Content.Headers.ContentDisposition = contentDisposition;
}
return this.ResponseMessage(result);
}
Based on what you are showing here, the parameter DosyaAdi is a string and it is not clear what DownloadInput is.根据您在此处显示的内容,参数 DosyaAdi 是一个字符串,不清楚 DownloadInput 是什么。 I would suggest changing the input parameter to a string and also changing the Method to HttpGet.
我建议将输入参数更改为字符串,并将方法更改为 HttpGet。 The second suggestion is for convention and probably not the issue.
第二个建议是为了惯例,可能不是问题。
// GET: api/Calendar/DownloadFile
[HttpGet]
public HttpResponseMessage DownloadFile(string DosyaAdi)...
good luck祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.