【发布时间】:2013-10-30 11:59:55
【问题描述】:
在我的网站中,我实施了部分 CMS。用户将能够完成的功能之一是上传各种文件以链接到他们认为必要的任何页面。我在服务器端的 C# 中使用 AJAX 和 System.IO 让用户能够上传或删除给定目录中的文件。
除此之外,他们还可以在编辑时实时预览页面。一切都很顺利,直到我尝试刷新预览(使用 javascript)在一个已经被路径到的文件被删除。
刚刚删除的文件的路径应该显示一个损坏的链接,但它仍然显示正确的图片(即使检查并手动刷新服务器端目录,显示它实际上,不存在)。
我在这里看到了这个 SO 问题:Auto refresh file or directory in WebApplication 但它似乎不一定适用于我的情况(否则为什么我在添加图片而不是删除图片时不会出现问题)?
我花了几个小时检查我的 JavaScript/jQuery 以确保我没有忽略任何东西,但它都是通过一个函数进行的,当涉及到刷新时,它应该一直工作或一直中断,有时不是其中之一。
图片是否仍然存在于客户端某处,即使从服务器端删除后? (同样,img 标记的 src 属性指向已被 C# File.Delete(Server.MapPath("~/CMS Files/" + location + "/" + file)); 删除的文件
Ajax 函数:
function deleteFile(event) {
var fileToDelete = event.parent().find(".fileDiv").text();
var fileLocation = $("input#pageLocation").val();
var confirmation = confirm("Are you sure you want to permanently delete the file, \"" + fileToDelete + "\" from the \"" + fileLocation + "\" File Box?");
if (confirmation) {
$.ajax({
url: "/AJAX Pages/Compute_Delete_File.cshtml",
async: false,
type: "POST",
data: { location: fileLocation, file: fileToDelete },
success: function (response) {
refreshFileBoxes(); //<--Self made function that refreshes the boxes (again, using AJAX) that collect what files are in the directory. Funny that this part always reflects correctly, the existing files in the server-side directory.
alert(response);
updatePreview(); //<--This function recollects all the page data in an array of objects, and refreshes the preview accordingly.
},
error: function (jqXHR, textStatus, error) {
alert("Oops! It appears there has been an AJAX error. You may need to refresh the page. Please save your work and refresh the page to see all files in the File Box.");
}
});
}
}
Ajax 函数指向的服务器端代码:
@{
Layout = "";
if (IsAjax)
{
var file = Request.Form["file"];
var location = Request.Form["location"];
File.Delete(Server.MapPath("~/CMS Files/" + location + "/" + file));
@:The file "@file" has been deleted.
}
else
{
Context.RedirectLocal("~/");
}
}
用于预览的 HTML
<div class="editPreview">
<div id="Library" class="contentWrapper">
<hr/>
<p class="pageTitle">Library</p>
<hr/>
<div class="contentImageWrapper" sytle="max-width: 375px;">
<img class="contentImgMedium" src="/CMS Files/Library/Okmulgee_Library.jpg" title="Okmulgee_Library.jpg" alt="Okmulgee_Library.jpg" />
</div>
<p class="contentParagraph" style=" text-align: center;">For more information about the Okmulgee Public Library, call (918)-756-1448.</p>
<br/>
<span class="contentText">Or visit their website at </span>
<a class="contentLink" href="http://www.fakewebaddress.com" target="_blank">http://www.fakewebaddress.com</a>
<br/>
<hr/>
</div>
</div>
您可能需要了解的事项:
我在 C#.net 网页环境中(带有 WebMatrix) 我愿意提供更多所需的代码,但所有文件路径的性质,恐怕让 jsfiddle 成为不可能。
【问题讨论】: