Kevorkian
Kevorkian

Reputation: 420

Not allowed to load local resource Error

I want to show the uploaded image after uploading it but I can not. I get an error from my JS console saying: Not allowed to load local resource Error

Here is my code :

Controller Method :

get file and save it to localsystem

[HttpPost]
// public static readonly string TEMPORARY_FILES_UPLOADS_PATH = "~/Uploads/Tmp";     
public ActionResult UploadFileToTemporaryFolder(HttpPostedFileBase file)
            {
                string fileName = String.Empty;
                string path = String.Empty;
                if (file != null)
                {
                    try
                    {
                       string timestamp = DateTime.UtcNow.ToString("yyyy_MM_dd_HH_mm_ss_fff",CultureInfo.InvariantCulture);
                       fileName = timestamp + "_" + Path.GetFileName(file.FileName);
                       path = string.Format("{0}/{1}", Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH), fileName);
                        System.IO.Directory.CreateDirectory(Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH));
                        file.SaveAs(path);
                    }
                    catch (Exception)
                    {}
                }
                return Json(new { FileName = fileName, FilePath=path }, JsonRequestBehavior.AllowGet);
            }

HTML :

<input id="HotelJustificatifFile" type="file" value="joindre pièce" name="upload"  >
<div id="JustificatifsHotelSection" style="display:block;"></div>

Js

Upload file & append result to a div

 $('body').on('change', '#HotelJustificatifFile', function () {

               var file = document.getElementById('HotelJustificatifFile').files[0];
               if (file != null) {
                   var myData = new FormData();
                   myData.append("file", file);

                   // Uploading File via Ajax To Temporar Folder
                   $.ajax({
                       type: "POST",
                       url: "<%: Url.Action("UploadFileToTemporaryFolder","Enqueteur") %>",
                       processData: false,
                       contentType: false,
                       data: myData,
                       cache: false,
                       dataType: "json",
                       success: function (result) {
                           if (result.FileName != '') {

                               var fileName = result.FileName;
                               var filePath = result.FilePath;

                               //alert(filePath );
                               var imageDiv = "<div>";
                               imageDiv+='<div style="z-index: 10; position: absolute; top: 4px; left: 10px;">';
                               imageDiv += '<a onclick="afficherImage(' + fileName + ')" >Supprimer</a>';
                               imageDiv +='</div>';
                               imageDiv += '<img u=image src="' +filePath + '" />';
                               imageDiv += '</div>';
                               // Adding Image To the Div 
                               $('#JustificatifsHotelSection').append(imageDiv);

                           }
                           },
                       failure: function () {
                       }
                   });

                   // Else
                }
           });

Upvotes: 2

Views: 27364

Answers (5)

Maishidh Mandviwala
Maishidh Mandviwala

Reputation: 62

You just need to replace all image network paths(or local path) with byte strings in stored Encoded HTML sting. For this you required HtmlAgilityPack to convert Html string to Html document. https://www.nuget.org/packages/HtmlAgilityPack

Find Below code to convert each image src network path(or local path) to byte sting. It will definitely display all images with network path(or local path) in IE,chrome and firefox.

string encodedHtmlString = Emailmodel.DtEmailFields.Rows[0]["Body"].ToString();

            // Decode the encoded string.
            StringWriter myWriter = new StringWriter();
            HttpUtility.HtmlDecode(encodedHtmlString, myWriter);
            string DecodedHtmlString = myWriter.ToString();

            //find and replace each img src with byte string
             HtmlDocument document = new HtmlDocument();
             document.LoadHtml(DecodedHtmlString);
             document.DocumentNode.Descendants("img")
              .Where(e =>
            {
                string src = e.GetAttributeValue("src", null) ?? "";
                return !string.IsNullOrEmpty(src);//&& src.StartsWith("data:image");
            })
            .ToList()
                        .ForEach(x =>
                        {
                            string currentSrcValue = x.GetAttributeValue("src", null);                                
                            string filePath = Path.GetDirectoryName(currentSrcValue) + "\\";
                            string filename = Path.GetFileName(currentSrcValue);
                            string contenttype = "image/" + Path.GetExtension(filename).Replace(".", "");
                            FileStream fs = new FileStream(filePath + filename, FileMode.Open, FileAccess.Read);
                            BinaryReader br = new BinaryReader(fs);
                            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                            br.Close();
                            fs.Close();
                            x.SetAttributeValue("src", "data:" + contenttype + ";base64," + Convert.ToBase64String(bytes));                                
                        });

            string result = document.DocumentNode.OuterHtml;
            //Encode HTML string
            string myEncodedString = HttpUtility.HtmlEncode(result);

            Emailmodel.DtEmailFields.Rows[0]["Body"] = myEncodedString;

Upvotes: 0

Isaac Lyman
Isaac Lyman

Reputation: 2205

I'd like to point out that Javascript can do this on its own, without sending the file through an API at all.

Web pages aren't allowed to dork around with files on the user's computer (physical file paths beginning with file:///), and I'm glad they aren't. Do you want random people on the Internet playing with stuff on your computer? Of course you don't.

Luckily, you can access any file the user chooses to upload (via a file input) using a data url (these begin with data:[MIME type];base64,), and you can get one via Javascript's built-in FileReader object. See below:

var previewImage = document.getElementById('my-preview');

var filereader = new FileReader();
filereader.onload = function (event) {
  var data = event.target.result;

  previewImage.src = data;
};

var file = document.getElementById('file-input').files[0];
filereader.readAsDataUrl(file);

Basically, this uses the FileReader to turn the user's uploaded file into a base64 data: URL, which you are free to use however you want (and the <img> tag isn't afraid to use it as a src attribute).

That's a win. You've got your preview image and you didn't have to get around sensible browser security to do it.

Upvotes: 1

Kevorkian
Kevorkian

Reputation: 420

i resolved the probleme , here is my controller method :

    [HttpPost]
            public ActionResult UploadFileToTemporaryFolder(HttpPostedFileBase file)
            {
                string fileName = String.Empty;
                string path = String.Empty;
                if (file != null)
                {
                    try
                    {
                       string timestamp = DateTime.UtcNow.ToString("yyyy_MM_dd_HH_mm_ss_fff",CultureInfo.InvariantCulture);
                       fileName = timestamp + "_" + Path.GetFileName(file.FileName);
                      // Relative Path ex "/uploads/Tmp"
                       path = Url.Content(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH);
                       System.IO.Directory.CreateDirectory(Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH));
                       // absolute path : C://........../uploads/Tmp
                       string fileSystemPath = string.Format("{0}/{1}", Server.MapPath(ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH), fileName);
                       file.SaveAs(fileSystemPath);
                    }
                    catch (Exception)
                    {}
                }
               // i send the relative path + filename
                return Json(new { FileName = fileName, FilePath=path }, JsonRequestBehavior.AllowGet);
            }

And I get The Path in my Js Code like that :

success: function (result) {
                           if (result.FileName != '') {

                               var fileName = result.FileName;
                               var filePath = result.FilePath;

                               //alert(filePath );
                                var imageDiv = '<div>';
                                imageDiv+='<div style="z-index: 10; position: absolute; top: 4px; left: 10px;">';
                                        imageDiv += '<a onclick="afficherImage(' + fileName + ')" >Supprimer</a>';
                                     imageDiv +='</div>';
                                     imageDiv += '<img style="width:100%; height:500px" u=image src="' +filePath +'/'+fileName+ '" />';
                                   imageDiv += '</div>';
                               // Adding Image To the Div 
                                   $('#HotelJustifS').append(imageDiv);

                           }
                           }

Upvotes: 0

adrianillo
adrianillo

Reputation: 49

you can not return the physical file path

Tries to return the image url (http: //...../imageName)

Or you can use html5 API to show images in the browser without having to upload the image to the server:

var file = document.getElementById(HotelJustificatifFile).files[0];
var reader = new FileReader();
var img = new Image();
img.src = reader.result;
youDivContainerForImage.appendChild(img);

Upvotes: 2

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

You are returning physical file path consider this instead:

var virtualPath=Url.Content(string.Format("{0}/{1}",
    ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH, fileName));

return Json(new { FileName = fileName, FilePath=virtualPath}, 
    JsonRequestBehavior.AllowGet);

Upvotes: 1

Related Questions