Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
XMLHttpRequest content-disposition null issue

This is my controller.

  [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
            };
        }

These are my response headers according to 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.NET 

But whenever I attempt to access the content-disposition header from Javascript, it returns null. I'm making an XMLHttpRequest.

 var contentDisposition = this.getResponseHeader('content-disposition'); 

Does my server-side code have any issues that could be causing this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Below is my work Post demo, you can refer to it.

FileAPIController.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;
    }
}

Privacy.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>

Result:

enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda