我有一张照片,我可以上传到我的项目中,并在数据库中关于我的照片存储的信息。这是我的数据库记录如何看起来像: 编号:1,路径:〜/上传/ d8cd7f97-1da2-43f3-b43a-74e5c9f28731.JPG DispayName:9.jpg,IsMainImage:没错, FurnitureId:25。 因此,这里是我的方法,其中包括服务器和数据库删除文件:如何从服务器上正确删除文件
[HttpPost]
public JsonResult DeleteFile(int Id)
{
try
{
FurnitureImages furnitureImages = db.FurnitureImages.Find(Id);
if (furnitureImages == null)
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return Json(new { Result = "Error" });
}
//Remove from database
db.FurnitureImages.Remove(furnitureImages);
db.SaveChanges();
//Delete file from the file system
var path = Server.MapPath(furnitureImages.Path);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
在我看来,我通过parametr阿贾克斯:
<script type="text/javascript">
$('.deleteItem').click(function (e) {
e.preventDefault();
var $ctrl = $(this);
if (confirm('Do you really want to delete this file?')) {
$.ajax({
url: '@Url.Action("DeleteFile")',
type: 'POST',
data: { Id: $(this).data('Id') }
}).done(function (data) {
if (data.Result == "OK") {
$ctrl.closest('li').remove();
}
else if (data.Result.Message) {
alert(data.Result.Message);
}
}).fail(function() {
alert("There is something wrong. Please try again.");
})
}
});
</script>
最后调用这个函数:
@for (int i = 0; i < Model.SecondaryImages.Count; i++)
{
@Html.HiddenFor(m => m.SecondaryImages[i].Id)
@Html.HiddenFor(m => m.SecondaryImages[i].Path)
@Html.HiddenFor(m => m.SecondaryImages[i].DisplayName)
<img src="@Url.Content(Model.SecondaryImages[i].Path)" />
<a href="javascript:void(0);" data-id="@Model.SecondaryImages[i].Id" class="deleteItem">X</a>
}
这个例子中的模型是ViewModel。但它不起作用,它写道:“有什么问题,请再试一次”,第一个条件如果不起作用,出了什么问题?由于
您是否打过F12并检查服务器响应? – CodeCaster
@CodeCaster嗨,我看到一个控制台,当我尝试删除它写在这里:POST http:// localhost:61741/Furnitures/DeleteFile 500(内部服务器错误)。我的代码有问题 –
因此,检查日志以查看错误是什么。或者附加调试器,并通过代码来查看发生了什么。 – mason