如何下载上传的文件?

时间:2015-06-03 17:04:42

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

我是Visual Studio MVC4 C#的初学者。我想获取上传文件,然后列出文件并为每个文件添加一个按钮,以允许用户将文件保存在他们的计算机中。

这是我的模特:

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


}

这是我的控制器

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

这是我的上传文件视图:

&#13;
&#13;
@{
    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>
}
&#13;
&#13;
&#13;

现在我的问题是,我收到了这个错误:

  

类型&#39; System.IO.DirectoryNotFoundException&#39;的例外情况发生了   在mscorlib.dll中但未在用户代码中处理   信息:找不到路径的一部分   &#39; C:\用户\阿比尔\桌面\ Watheq \ Watheq \程序App_Data \上传\ 20131220_130423.jpg&#39;

我不知道如何显示上传的文件并下载它们。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

IIS的权限问题通常表明它没有访问权限,而不是无法找到该文件。

当您尝试保存目录不存在的文件时,您会看到该错误。在您的代码中,您只是写入文件夹,但不检查目录是否存在。见下文。

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

file.SaveAs(path);