在 MVC 5 中上传和下载文件

本文关键字:下载 文件 MVC | 更新日期: 2023-09-27 18:35:42

我是C#和 ASP.NET MVC的新手。
我正在尝试上传文件,并能够在Visual Studio 2013中根据其依赖项下载它们。
我有委派模型:

public int idDelegation { get; set; }
public string Delegation_Name { get; set; }
public string Employee_Name { get; set; }
public virtual ICollection<Doc> Doc { get; set; }

和文档模型:

public int idDoc { get; set; }
public int idDelegation { get; set; }
public string Doc_Name { get; set; }
public DateTime Doc_Validity_Date { get; set; }
public byte[] Content { get; set; }
public virtual Delegation Delegation { get; set; }

我试图做的是上传与代表团相关的文件。
所以我尝试了不同的方法来做到这一点,包括将它们保存到服务器或数据库中。
尝试将它们保存在数据库中,我在DocsController中创建了方法UploadDoc():

    [HttpPost]
    public ActionResult UploadDoc(HttpPostedFileBase file)
    {
        string path = Server.MapPath(@"LocalPath'" + file.FileName);
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath(path), fileName);
            file.SaveAs(path);
        }
        byte[] uploadedFile = new byte[viewModelDoc.file.InputStream.Length];
        viewModelDoc.file.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
        return RedirectToAction("Index");
    }  

我在DocsController的HttpPost Create方法中调用了它:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "idDoc,idDoc_Type,idDelegation,Doc_Name,Doc_Validity_Date, Content, FileMimeType")] Doc doc, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            UploadDoc(doc, file);
            db.Doc.Add(doc);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.idDelegation = new SelectList(db.Delegation, "idDelegation", "Delegation_Name", doc.idDelegation);
        ViewBag.idDoc_Type = new SelectList(db.Doc_Type, "idDoc_Type", "Doc_Type_Name", doc.idDoc_Type);
        return View(doc);
    }  

我创建了ViewModel UploadDoc:

public class UploadDoc
    {
        public int idDoc { get; set; }
        public string Doc_Name { get; set; }
        public DateTime Doc_Validity_Date { get; set; }
        public byte[] Content { get; set; }
        public virtual Delegation Delegation { get; set; }
        public HttpPostedFileBase file { get; set; }
     }  

然后,在我的 Create.cshtml 视图中:

<div class="form-group">
            I
            @using (Html.BeginForm("UploadDoc", "Docs",
                        FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
        {
               <div class="col-md-10">
                @Html.TextBoxFor(x => x.file, new { type = "file" })
                @Html.ValidationMessageFor(x=>x.file)
                <button type="submit"> Upload </button>
                </div>
        }
</div>  

不幸的是,应用程序在数据库中创建了有关文档(文件)的条目(如Doc_Name和其他属性),但文件未上传。
另一种方法,试图将它们保存在服务器上,也有相同的结果。
请帮忙。我为这个问题苦苦挣扎了一个多星期。
谢谢。

在 MVC 5 中上传和下载文件

Controller
[HttpPost]
        public ActionResult Save(List<HttpPostedFileBase> fileUpload, TicketSystemAPI.Models.Tickets.Ticketss ticket)
        {
            if (!Helper.Common.LogedInUser())
                return RedirectToAction("Login", "Logins");
            List<string> myTempPaths = new List<string>();
            if (fileUpload.Count > 1)
            {

                foreach (var file in fileUpload)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        int MaxContentLength = 1024 * 1024 * 3; //3 MB
                        string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png" };
                        if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                        {
                            ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                            TempData["error"] = ("Please file of type: " + string.Join(", ", AllowedFileExtensions));
                            // return ("TicketsEdit",TempData["error"].ToString());
                        }
                        else if (file.ContentLength > MaxContentLength)
                        {
                            ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                        }
                        else
                        {
                            string extension = Path.GetExtension(file.FileName);
                            string fileName = DateTime.Now.ToString("ddMMyyHHmmss").ToString() + extension;
                            //         TempData["FileName"] = fileName;

                            //var filename = Guid.NewGuid() + Path.GetFileName(file.FileName);
                            //file.SaveAs(Path.Combine(Server.MapPath("~/Attach/Document"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
                            file.SaveAs(Path.Combine(Server.MapPath("~/Attach/Document"), fileName + Path.GetExtension(file.FileName)));
                            ModelState.Clear();
                            //       ViewBag.Message = "File uploaded successfully";
                            myTempPaths.Add(fileName);
                        }
                    }
                }
            }

View 

@using (Html.BeginForm("Save", "Tickets",
FormMethod.Post, new { enctype = "multipart/form-data", id = "frmID" }))
{
    @Html.HiddenFor(i => i.FileName)
    <div class="labelstyle">
        <label>Files</label>
    </div>
    <div id="uploaders">
        <input type="file" id="fileToUpload"
               name="fileUpload" multiple="multiple" style="float: left;" />
        <br />
        <span id="spnFile" style="float: left; color: #FF0000"></span>
        @Html.ValidationMessage("File")
        @Html.Hidden("hdnFileUpload")
    </div>
    <br />
    <div class="col-lg-6">
        <button class="btn btn-primary" id="btnAddIssue" type="submit">Submit</button>
    </div>
    <br />
    <div class="control-section" style="padding: 0px;">
        <div id="selectedFiles"></div>
    </div>
}