I have a project in the ASP.NET Web API which is consumed by a web application in html, I have a form in which I sent information and a PDF file, this is done with formdata
, the PDF file is saved in a folder on the server with the original extension and a name assigned to it, the other data I keep in the database, as well as the name assigned to the file.
All this works correctly. My question is how can I visualize that file that I uploaded to the server (I am working locally) through the web application, and that is displayed in the browser. I have researched a lot but I still have not found the solution to the problem.
Through the button I identify the ID of the record in the database, to later retrieve the name of the file in the database and identify the route where the file is located. This is the function that executes the button:
VerDocumento:
function (param) {
var IdDoc = param;
var IdPerAlumno = $('#IdPerAlumno').val();
if (IdDoc) {
$.ajax({
type: "GET",
url: URLExpediente,
data: { IdRegDocumento: IdDoc, IdPerAlumno: IdPerAlumno },
contentType: 'application/pdf',
cache: false,
success: function (resultado) {
var blob = new Blob([resultado]);
var link = document.createElement('blob');
link.setAttribute('data', blob);
link.setAttribute('type', 'application/pdf');
window.open(document.body.appendChild(link), "_blank");
},
error: function () {
alert("No se ha subido un archivo para este documento registrado");
}
});
} else {
alert("Por favor seleccione un Aspirante");
}
}
The Ajax URL is the Web API driver that has the method to search the file that is on the server. This is the Driver called File and the method that performs the search of the PDF file.
Search PDF document:
[HttpGet]
public HttpResponseMessage MostrarPDF(int IdRegDocumento, int IdPerAlumno)
{
EXPEDIENTEALUMNO documentoExp = LGExpediente.GetExpediente().Find(x => x.IdReg == IdRegDocumento);
var NombreArchivo = documentoExp.NombreArchivo;
if (NombreArchivo == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound, NombreArchivo);
}
string path = "~/App_Data/" + IdPerAlumno + "/Expediente/" + NombreArchivo + ".pdf";
string root = HttpContext.Current.Server.MapPath(path);
if (File.Exists(root))
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(root, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound, root);
}
}
And in the url of the browser is: [object%20HTMLUnknownElement]
and the PDF file is not displayed in the browser.