2010-11-18 95 views
0

我想知道我從谷歌研究過的ASP.NET MVC2的兩件事情,但仍然令人困惑。希望我能在這裏找到清晰而乾淨的答案。文件上傳/下載ASP.NET MVC2中的示例?

首先,如何使用自定義文件路徑將文件上傳到服務器。 (例如/ Content/Files)

二,如何下載該文件,由於url已應用URL Rounting,如何映射到它們?

感謝您的回答!

回答

1

要上傳,您將使用類似這樣的內容。

<form action="/MyController/SaveDocuments/" method="post" enctype="multipart/form-data"> 

     <label for="file1">Document 1</label> 
     <input type="file" id="file1" name="file1" /> 

</form> 

而這裏的控制器上的代碼來保存文件:

 public Document[] SaveDocuments(HttpRequestBase iHttpRequest, Instruction instruction) 
    { 
     List<Document> documents = new List<Document>(); 

     foreach (string inputTagName in iHttpRequest.Files) 
     { 
      HttpPostedFile file = iHttpRequest.Files[inputTagName]; 
      if (file.ContentLength > 0) 
      { 
       if (Path.GetExtension(file.FileName).Length == 0) 
       { 
        throw new ValidationException(string.Format("File '{0}' has no extension (e.g. .doc .pdf)", file.FileName)); 
       } 
       string filePath = documentService.BuildDocumentPath(instruction.InstructionId, file.FileName); 
       file.SaveAs(filePath); 

       documents.Add(new Document 
       { 
        Filename = Path.GetFileName(file.FileName), 
        Path = filePath 
       }); 
      } 
     } 

     return documents.ToArray(); 
    } 

至於下載,說你有目錄「〜/內容/文件」 ......

你只需在你的路線中排除他們。

routes.IgnoreRoute("Content/{*pathInfo}");