[英]Not allowed to load local resource Error
我想在上傳后顯示上傳的圖像,但是不能。 我從JS控制台收到一條錯誤消息: Not allowed to load local resource Error
這是我的代碼:
控制器方式:
獲取文件並將其保存到本地系統
[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
上傳文件並將結果附加到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
}
});
您無法返回物理文件路徑
嘗試返回圖像網址(http://...../imageName)
或者,您可以使用html5 API在瀏覽器中顯示圖像,而不必將圖像上傳到服務器:
var file = document.getElementById(HotelJustificatifFile).files[0];
var reader = new FileReader();
var img = new Image();
img.src = reader.result;
youDivContainerForImage.appendChild(img);
不允許加載本地資源錯誤,可能是此鏈接可以解決您的問題.. http://www.scriptscoop.net/t/17cccd1064d6/angularjs-1-2-not-allowed-to-load-local-resource.html
您要返回物理文件路徑,請考慮以下內容:
var virtualPath=Url.Content(string.Format("{0}/{1}",
ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH, fileName));
return Json(new { FileName = fileName, FilePath=virtualPath},
JsonRequestBehavior.AllowGet);
我想指出的是,Javascript可以自己執行此操作,而根本不需要通過API發送文件。
網頁不允許與用戶計算機上的文件(以file:///
開頭的物理文件路徑) file:///
,我很高興他們沒有這樣做。 您是否希望互聯網上的隨機人在玩計算機上的東西? 當然不會。
幸運的是,您可以使用數據url(以data:[MIME type];base64,
開頭)訪問用戶選擇通過文件輸入上傳的任何文件,並且可以通過Javascript的內置FileReader
對象獲得一個。 見下文:
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);
基本上,這使用FileReader
將用戶上傳的文件轉換為base64 data:
URL,您可以隨意使用它(並且<img>
標簽不怕將其用作src
屬性)。
那是勝利。 您已經獲得了預覽圖像,而不必繞開明智的瀏覽器安全性來進行操作。
我解決了問題,這是我的控制器方法:
[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);
}
我在我的Js代碼中得到的路徑是:
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);
}
}
您只需要用存儲的已編碼HTML字符串中的字節字符串替換所有圖像網絡路徑(或本地路徑)即可。 為此,您需要HtmlAgilityPack將HTML字符串轉換為HTML文檔。 https://www.nuget.org/packages/HtmlAgilityPack
查找以下代碼將每個圖像src網絡路徑(或本地路徑)轉換為字節字符串。 它肯定會在IE,chrome和firefox中顯示具有網絡路徑(或本地路徑)的所有圖像。
字符串編碼的HtmlString = 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.