2015-06-03 139 views
0

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

這是我上傳的文件視圖:

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

現在我的問題是,我得到這個錯誤:

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'.

我不知道如何顯示上傳的文件並進行下載了。

感謝您的任何幫助。

+0

看起來好像你正在上傳它們......你的例外說明了這個目錄是否存在? – ragerory

+0

我相信這可能是一個安全問題。 IIS可能無法訪問該路徑。 –

回答

0

來自IIS的權限問題通常指出它沒有訪問權限,不是無法找到該文件。

這個錯誤是當你嘗試保存一個目錄不存在的文件時你會看到的。在您的代碼中,您只是寫入一個文件夾,但不檢查目錄是否存在。見下文。

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

file.SaveAs(path); 
+0

非常感謝你。問題解決.. – HamsAlrooh

+0

@HamsAlrooh沒問題 - 請標記爲答覆:) – ragerory

0

可能是一個權限問題,將該項目複製到另一個地方比你的桌面,然後嘗試。

+0

現在好了如何在列表中顯示上傳的文件並下載鏈接? – HamsAlrooh