我希望在上传后显示上传的图片,但我不能。我从JS控制台收到一条错误:Not allowed to load local resource Error
这是我的代码:
控制器方法:
获取文件并将其保存到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
上传文件&amp;将结果附加到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
}
});
答案 0 :(得分:2)
您无法返回物理文件路径
尝试返回图片网址(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);
答案 1 :(得分:1)
不允许加载本地资源错误,可能是此链接解决了您的答案.. http://www.scriptscoop.net/t/17cccd1064d6/angularjs-1-2-not-allowed-to-load-local-resource.html
答案 2 :(得分:1)
您将返回物理文件路径,而不是考虑这一点:
var virtualPath=Url.Content(string.Format("{0}/{1}",
ApplicationConfig.TEMPORARY_FILES_UPLOADS_PATH, fileName));
return Json(new { FileName = fileName, FilePath=virtualPath},
JsonRequestBehavior.AllowGet);
答案 3 :(得分:1)
我想指出,Javascript可以自行完成,而无需通过API发送文件。
不允许网页使用用户计算机上的文件(以file:///
开头的物理文件路径),我很高兴他们不是。你想让互联网上随机的人玩你电脑上的东西吗?当然你没有。
幸运的是,您可以使用数据网址(以data:[MIME type];base64,
开头)访问用户选择上传的任何文件(通过文件输入),您可以通过Javascript的内置{{1}获取一个文件对象。见下文:
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);
将用户上传的文件转换为base64 FileReader
网址,您可以随意使用该网址(并且data:
标记不是害怕将它用作<img>
属性。)
这是一场胜利。您已经获得了预览图像,并且您无需了解合理的浏览器安全性。
答案 4 :(得分:0)
我解决了问题,这是我的控制器方法:
[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 Code中得到了这样的路径:
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);
}
}
答案 5 :(得分:0)
您只需要用存储的已编码HTML字符串中的字节字符串替换所有图像网络路径(或本地路径)即可。 为此,您需要HtmlAgilityPack将HTML字符串转换为HTML文档。 https://www.nuget.org/packages/HtmlAgilityPack
查找以下代码,将每个图像src网络路径(或本地路径)转换为字节字符串。 它肯定会在IE,chrome和firefox中显示具有网络路径(或本地路径)的所有图像。
string encodingHtmlString = 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;