在MVC 5中上传和下载文件

时间:2016-02-22 09:35:38

标签: c# asp.net-mvc-5

我是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; }

和Doc模型:

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; }

我要做的是上传与该代表团相关的文档。
所以我尝试了不同的方法,包括将它们保存到服务器或数据库中 试图将它们保存在DB中,我在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和其他属性),但文件不会上传。
试图将它们保存在服务器上的另一种方法也有相同的结果 请帮忙。我在这个问题上挣扎了一个多星期 谢谢。

1 个答案:

答案 0 :(得分:0)

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>
}