admin管理员组文章数量:1287150
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
}
});
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
}
});
Share
Improve this question
edited Oct 6, 2015 at 11:28
Kevorkian
asked Oct 6, 2015 at 11:24
KevorkianKevorkian
4202 gold badges4 silver badges14 bronze badges
2
-
Looks like you are returning the servers local path (e.g.
C:\uploads\blah.jpg
not the URLhttp://myserverrocks./images/blah.jpg
– AlG Commented Oct 6, 2015 at 11:29 - that's correct , how to resolve that ? – Kevorkian Commented Oct 6, 2015 at 12:40
5 Answers
Reset to default 2you 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);
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);
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 puter (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 puter? 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.
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);
}
}
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/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;
本文标签: javascriptNot allowed to load local resource ErrorStack Overflow
版权声明:本文标题:javascript - Not allowed to load local resource Error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741275501a2369703.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论