简体   繁体   中英

How to download the uploaded files?

I am beginner in Visual Studio MVC4 C#. I would like to get the Upload files and then list the files and put a button for each file to allow the users to save the files in their computer.

This is my model:

public class UploadDocModel
{

    private System.IO.FileInfo file;

    public int Id { get; set; }
    public string UserName { get; set; }
    public string Path { get; set; }
    public string FileName { get; set; }
    public DateTime Date { get; set; }

    //add constructor
    public UploadDocModel() { }
    public UploadDocModel(int _Id, string _FileName)
    {
        this.Id = _Id;
        this.FileName = _FileName;
    }

    public UploadDocModel(System.IO.FileInfo file)
    {
        // TODO: Complete member initialization
        this.file = file;
    }


}

this is My Controller

public class UploadController : Controller
{

    public ActionResult UploadDownloadFiles()
    {
        try
        {
            List<UploadDocModel> ContentFiles = new List<UploadDocModel>();

            List<FileInfo> files = this.DirectoryFileList;

            foreach (FileInfo file in files)
            {
                UploadDocModel _UploadDocModel = new UploadDocModel(file);
                if (_UploadDocModel != null) ContentFiles.Add(_UploadDocModel);

            }

            return View(ContentFiles);
        }
        catch
        {
            return RedirectToAction("ConnectionError", "Home");
        }
    }




    public ActionResult FileUpload()
    {
        return View();
    }

    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            if (file == null)
            {
                ModelState.AddModelError("File", "Please Upload Your file");
            }
            else if (file.ContentLength > 0)
            {
                int MaxContentLength = 1024 * 1024 * 3; //3 MB
                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };

                if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                {
                    ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                }

                else if (file.ContentLength > MaxContentLength)
                {
                    ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                }
                else
                {
                    //TO:DO
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/App_Data/Upload"), fileName);
                    file.SaveAs(path);
                    //return View((object)path);
                 ModelState.Clear();
                 ViewBag.Message = "File uploaded successfully";
                }
            }
        }
        return RedirectToAction("UploadDownloadFiles", "Upload");
    }
    public ActionResult Download(string fn)
    {
        try
        {
            return new DownloadResult { VirtualPath = "~/App_Data/Upload" + fn, FileDownloadName = fn };
        }
        catch
        {
            return RedirectToAction("ConnectionError", "Home");
        }
    }

    public List<FileInfo> DirectoryFileList
    {
        get
        {
            DirectoryInfo directory = new DirectoryInfo(Path.Combine(HttpRuntime.AppDomainAppPath, "~/App_Data/Upload"));
            return directory.GetFiles().ToList<FileInfo>();
        }
    }

}


This is my Download Result Class




 public class DownloadResult : ActionResult
{
    public DownloadResult()
    {
    }

    public DownloadResult(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath { get; set; }

    public string FileDownloadName { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        try
        {
            if (!String.IsNullOrEmpty(FileDownloadName))
            {
                context.HttpContext.Response.AddHeader("content-disposition",
                  "attachment; filename=" + this.FileDownloadName);
            }

            string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
            context.HttpContext.Response.TransmitFile(filePath);
        }
        catch
        {
        }
    }
}

This is my upload file view:

 @{ ViewBag.Title = " File Upload"; } <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script> <script type="text/jscript"> //get file size function GetFileSize(fileid) { try { var fileSize = 0; //for IE if ($.browser.msie) { //before making an object of ActiveXObject, //please make sure ActiveX is enabled in your IE browser var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value; var objFile = objFSO.getFile(filePath); var fileSize = objFile.size; //size in kb fileSize = fileSize / 1048576; //size in mb } //for FF, Safari, Opeara and Others else { fileSize = $("#" + fileid)[0].files[0].size //size in kb fileSize = fileSize / 1048576; //size in mb } // alert("Uploaded File Size is" + fileSize + "MB"); return fileSize; } catch (e) { alert("Error is :" + e); } } //get file path from client system function getNameFromPath(strFilepath) { var objRE = new RegExp(/([^\\/\\\\]+)$/); var strName = objRE.exec(strFilepath); if (strName == null) { return null; } else { return strName[0]; } } $("#btnSubmit").live("click", function () { if ($('#fileToUpload').val() == "") { $("#spanfile").html("Please upload file"); return false; } else { return checkfile(); } }); function checkfile() { var file = getNameFromPath($("#fileToUpload").val()); if (file != null) { var extension = file.substr((file.lastIndexOf('.') + 1)); // alert(extension); switch (extension) { case 'jpg': case 'png': case 'gif': case 'pdf': flag = true; break; default: flag = false; } } if (flag == false) { $("#spanfile").text("You can upload only jpg,png,gif,pdf extension file"); return false; } else { var size = GetFileSize('fileToUpload'); if (size > 3) { $("#spanfile").text("You can upload file up to 3 MB"); return false; } else { $("#spanfile").text(""); } } } $(function () { $("#fileToUpload").change(function () { checkfile(); }); }); </script> <h2>Upload File</h2> <h3 style="color:green">@ViewBag.Message</h3> @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(); <fieldset> <legend>Registration Form</legend> <ol> <li class="lifile"> <input type="file" id="fileToUpload" name="file" /> <span class="field-validation-error" id="spanfile"></span> </li> </ol> <input type="submit" id="btnSubmit" value="Upload" /> </fieldset> } 

Now my problem is, I get this error:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code Additional information: Could not find a part of the path 'C:\\Users\\Abeer\\Desktop\\Watheq\\Watheq\\App_Data\\Upload\\20131220_130423.jpg'.

I don't know how to display the uploaded files and download them too.

Thanks for any help.

可能是权限问题,请将项目复制到桌面以外的其他位置,然后尝试。

A permission issue from IIS generally states that it doesn't have access, not that the file could not be found.

That error is what you'll see when you try and save a file where the Directory doesn't exist. In your code, you're just writing to a folder, but not checking if the Directory exists first. See below.

if (!Directory.Exists(Server.MapPath("~/App_Data/Upload")))
{
    Directory.CreateDirectory(Server.MapPath("~/App_Data/Upload"));
}

file.SaveAs(path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM