代码之家  ›  专栏  ›  技术社区  ›  user469652

在ASP.NET MVC2中上载/下载示例文件?

  •  0
  • user469652  · 技术社区  · 14 年前

    我想知道两件事,关于ASP.NET MVC2,我已经从谷歌研究过,但仍然困惑。希望我能在这里找到清晰的答案。

    首先,如何使用自定义文件路径将文件上载到服务器。(例如to/Content/Files)

    其次,如何下载该文件,既然url已经应用了url Rounting,如何映射到它们?

    谢谢你的回答!

    1 回复  |  直到 14 年前
        1
  •  1
  •   Chase Florell    14 年前

    要上传,您将使用这样的东西。

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

    至于下载,假设你有目录“~/Content/Files”。。。

    你只需要在你的路线上排除他们。

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