ASP.NET Core Content-Disposition attachment/inline
Я возвращаю файл из контроллера WebAPI. Значение заголовка Content-Disposition автоматически устанавливается на "вложение". Например:
Планировка: вложение; имя файла = "30956.pdf"; Имя файла * = UTF-8''30956.pdf
Когда он настроен на вложение, браузер попросит сохранить файл, а не открывать его. Я бы хотел, чтобы он открыл его.
Как я могу установить его на "inline" вместо "attachment"?
Я отправляю файл, используя этот метод:
public IActionResult GetDocument(int id)
{
var filename = $"folder/{id}.pdf";
var fileContentResult = new FileContentResult(File.ReadAllBytes(filename), "application/pdf")
{
FileDownloadName = $"{id}.pdf"
};
// I need to delete file after me
System.IO.File.Delete(filename);
return fileContentResult;
}
Ответы
Ответ 1
Лучший способ, который я нашел, - это добавить заголовки содержимого.
private IActionResult GetFile(int id)
{
var file = $"folder/{id}.pdf";
// Response...
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = file,
Inline = displayInline // false = prompt the user for downloading; true = browser to try to show the file inline
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return File(System.IO.File.ReadAllBytes(file), "application/pdf");
}
Ответ 2
Учитывая, что вы не хотите читать файл в памяти сразу в массиве байтов (используя различные перегрузки File(byte[]...)
или используя FileContentResult
), вы можете использовать перегрузку File(Stream, string, string)
, где последний параметр указывает имя, под которым файл будет представлен для загрузки:
return File(stream, "content/type", "FileDownloadName.ext");
Или вы можете использовать существующий тип ответа, поддерживающий потоковое вещание, например FileStreamResult
, и самостоятельно настройте содержимое. Канонический способ сделать это, как показано в FileResultExecutorBase
, состоит в том, чтобы просто настроить заголовок на ответ в вашем методе действий:
// Set up the content-disposition header with proper encoding of the filename
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName("FileDownloadName.ext");
Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
// Return the actual filestream
return new FileStreamResult(@"path\to\file", "content/type");
Ответ 3
попробуйте с помощью HttpResponseMessage
public IActionResult GetDocument(int id)
{
var filename = $"folder/{id}.pdf";
Response.Headers["Content-Disposition"] = $"inline; filename={id}.pdf";
var fileContentResult = new FileContentResult(System.IO.File.ReadAllBytes(filename), "application/pdf")
{
FileDownloadName = $"{id}.pdf"
};
// I need to delete file after me
System.IO.File.Delete(filename);
return fileContentResult;
}
Ответ 4
Поскольку File()
игнорирует Content-Disposition
, я использовал это:
Response.Headers[HeaderNames.ContentDisposition] = new MimeKit.ContentDisposition { FileName = fileName, Disposition = MimeKit.ContentDisposition.Inline }.ToString();
return new FileContentResult(System.IO.File.ReadAllBytes(filePath), "application/pdf");
и он работает: -)