你好,我创建了一个非常简单的文件上传器:
Model:
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Web;
using System.Web.WebPages.Html;
namespace BestPractices.Models
{
public class AddPracticeModel
{
public Guid folder { get; set; }
[Display(Name = "Attachments:")]
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
}
Controller:
public ActionResult AddPractice()
{
form.folder = Guid.NewGuid();
return View(form);
}
[HttpPost]
public ActionResult AddPractice(AddPracticeModel formData, string FilePath)
{
if (ModelState.IsValid)
{
//Send To DB
}
else{
foreach (var files in formData.Files)
{
try
{
if (files != null)
{
var dir = Server.MapPath("/Attachments/" + formData.folder.ToString());
if (!Directory.Exists(dir))
{
System.IO.Directory.CreateDirectory(dir);
var fileName = Path.GetFileName(files.FileName);
var path = Path.Combine(dir, fileName);
files.SaveAs(path);
}
else
{
var fileName = Path.GetFileName(files.FileName);
var path = Path.Combine(dir, fileName);
files.SaveAs(path);
}
}
}
catch
{
}
}
}
return View(formData);
}
详细情况是:我为此表格创建了一个Guid,该Guid将成为一个存储特定练习文件的文件夹。这样,我就可以返回文件夹内容,以便人们可以下载它们和做其他事。
View:
<div class="formBody">
@using (Html.BeginForm("AddPractice", "Main", FormMethod.Post, new { enctype = "multipart/form-data", id="myForm" }))
{
<div class="inputFields">
@Html.LabelFor(x => x.Files)
@Html.TextBoxFor(x => x.Files, new { type = "file", multiple = "true" })
</div>
<div class="submitButton">
<input type="submit" value="Submit" onclick="document.getElementById('isRealSubmit').setAttribute('value','True');" />
</div>
@Html.TextBoxFor(x => x.folder, new { hidden = "true" })
var dir = Server.MapPath("/Attachments/" + Model.folder.ToString());
DirectoryInfo d = new DirectoryInfo(dir);
try {
<table>
@foreach (var file in d.GetFiles())
{
var dir2 = Server.MapPath("/Attachments/" + Model.folder.ToString() + "/" + file);
<tr>
<td><a style="color: red" href="/Attachments/@Model.folder.ToString()/@file" download>@file</a></td>
<td>@Html.ActionLink("Delete", "DeleteFile", new { FilePath = dir2 }, new { onclick="var r = confirm('Are you sure you would like to delete?'); if (r == true){document.getElementById('myForm').submit();}", target = "_blank" })</td>
@*<a href="#" id="Delete">Delete</a></td>*@
</tr>
}
</table>
}
catch
{
}
}
</div>
在发布时,如果添加了多个文件,它将在该文件夹中创建一个当前项目表。 但是,这里遇到了一些问题:第一个问题是必须发布该表单,以便我们可以对添加到文件夹中当前项目表中的新文档进行更新;然后删除项目,我必须阅读一个新页面:DeleteFile,它仅获取url并删除该项目;然后刷新主页以显示文件夹中的当前项目。但是,DeleteFile在新页面中打开后就会立即关闭。 这可能会使用户感到困惑,因为他们可能会看到一个打开的页面,然后看到页此快速地关闭。
有没有一种方法可以使页面上的文件管理器在不通过Jquery和Ajax发布的情况下进行更新?或者有没有一种删除项目的方法,而无需打开新页面,然后刷新我们的表单?
You may use ajax to delete a file.
It might not be a good idea to show the server path where you are showing the files to the user (user can do view source and see your folder structure). You may simply use the file name (I hope it is unique) instead of the full path.
So inside the loop,
<table>
@foreach (var file in d.GetFiles())
{
<tr>
<td><span>@file</span>
<a href="@Url.Action("DeleteFile", "Home",
new {fileName = file, folderName= Model.folder})" class="del">Delete</a>
</td>
</tr>
}
</table>
And now listen to the click event on this link. Using jQuery
$(function(){
$("a.del").click(function(e){
e.preventDefault();
if(window.confirm("are you sure to delete"))
{
var _this=$(this);
$.post(_this.attr("href"),function(res){
alert(res.MessagePort);
if (res.status === "success") {
_this.closest("tr").remove(); //remove the item from the UI
}
});
}
});
});
Assuming you have an action method called DeleteFile
inside your HomeController
which accepts the file path and delete it.
[HttpPost]
public bool DeleteFile(string filePath,string folderName)
{
var path = Server.MapPath(Path.Combine("~/Attachments/",folderName, fileName));
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
return Json( new { status="success", Message= "Deleted successfully"});
}
return Json(new { status = "success", Message = "No file!!!!" });
}