开发者

File uploading/Downloading samples in ASP.NET MVC2?

I want to know two things about ASP.NET MVC2 that I've researched from Google but still c开发者_如何学JAVAonfusing. Hope I can find clear and clean answer here.

First, how to upload a file to server with custom file path. (Eg. to /Content/Files)

Second, how to download that file, since the url has applied URL Rounting, how to map to them?

Thanks for your answers!


To upload, you'll use something like this.

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

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

</form>

And here's the code on the controller to save the file:

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

As for downloading, say you have the directory "~/Content/Files"...

You just have to exclude them in your route.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜