Este es mi controlador.
[HttpGet("GetFile")] [Authorize] public async Task<FileContentResult> GetFile([FromQuery] Guid fileId) { var fileName = string.Format("{0}.doc", _service.GetFileNameFromId(fileId)); var fileName = "someFile.doc"; var mimeType = "application/msword"; byte[] fileBytes = _service.GetFileByteArray(fileId); System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = fileName, Inline = false }; Response.Headers.Add("Content-Disposition", cd.ToString()); return new FileContentResult(fileBytes, mimeType) { FileDownloadName = fileName }; }Estos son mis encabezados de respuesta según Swagger.
content-disposition: attachment; filename="someFile.doc"; filename*=UTF-8''someFile.doc content-length: 3853 content-type: application/msword date: Thu31 Mar 2022 13:05:34 GMT server: Microsoft-IIS/10.0 x-powered-by: ASP.NETPero cada vez que intento acceder al encabezado de disposición de contenido desde Javascript, devuelve nulo. Estoy haciendo un XMLHttpRequest.
var contentDisposition = this.getResponseHeader('content-disposition');¿Mi código del lado del servidor tiene algún problema que podría estar causando esto?
A continuación se muestra mi trabajo Post demostración, puede consultarlo.
ArchivoAPIController.cs:
[Route("api/[controller]")] [ApiController] public class FileAPIController : ControllerBase { private IWebHostEnvironment webHostEnvironment; public FileAPIController(IWebHostEnvironment _webHostEnvironment) { webHostEnvironment = _webHostEnvironment; } [HttpPost("UploadFile")] public async Task<string> UploadFile([FromForm] IFormFile file) { string path = Path.Combine(this.webHostEnvironment.WebRootPath, "IFiles/", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition { FileName = file.FileName, Inline = false }; Response.Headers.Add("Content-Disposition", cd.ToString()); return "https://localhost:5001/IFiles/" + file.FileName; } }Privacidad.cshtml:
@{ ViewData["Title"] = "Privacy Policy"; } <h1>@ViewData["Title"]</h1> <p>Use this page to detail your site's privacy policy.</p> <input type="file" id="File" /> <button id="AddButton" onclick="UploadFile()" type="submit">Add</button> <script type="text/javascript"> function UploadFile() { var xhttp = new XMLHttpRequest(); xhttp.open("POST", "https://localhost:5001/api/FileAPI/UploadFile", true); data = new FormData(); data.append("file", document.getElementById("File").files[0]); xhttp.send(data); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var disposition =xhttp.getResponseHeader('Content-Disposition'); alert(this.response); } }; } </script>Resultado: