I am developing an application which allows me to bring some files saved from another server for that I have a code made in Asp.net which I consume with Javascript to bring the image, but when I get the image to show it, the following generates me error, Not allowed to load local resource: file: /// C: /Users/usuario/Desktop/imagenes/prfil/descarga.png, but when I copy the same link in the browser if it brings me the image:
This is my code .net:
public IHttpActionResult Get(string nombreArchivo) { string directorio = "C:UsersusuarioDesktopimagenes" string ruta = directorio + nombreArchivo; if (File.Exists(ruta)) { var result = new { imagen = ruta.Replace('\', '/') } return Ok(result); } else { var result = new { imagen = "No existe la imagen" } return Ok(result); } }
And this my code JavaScript:
const file = async () => { const res = await fetch(`http://localhost:64108/api/Archivos/?nombreArchivo=perfil/descarga.png`); const datos = await res.json(); foto.style.backgroundImage = `url('${datos.imagen}')`; };
Advertisement
Answer
Browsers use the local file://
protocol to load local files, which is only allowed for local calls. Same thing with HTTP protocol; it won’t work to use this protocol followed by the full path of a local file. Yet, you have at least two options here. You either provide a public folder within your application’s root directory, where you can access the file using a relative URI, which is the safer way of doing it.
Another possible approach is to return a file instead of a path. For this one, you may do something like this:
Javascript
let url = "http://localhost:64108/api/Archivos/?nombreArchivo=perfil/descarga.png"; let init = { method: 'GET', headers: { 'Accept': 'image/png' } }; fetch(url, init) .then(function (res) { // ... }) .catch(function (err) { // ... });
C#
public IHttpActionResult Get(string nombreArchivo) { string directorio = "C:\Users\usuario\Desktop\imagenes\"; string ruta = directorio + nombreArchivo; if (System.IO.File.Exists(ruta)) return File(path, Request.Headers["Accept"]); // We've already set this to "image/png" in the javascript part else return BadRequest("No existe la imagen"); }