【问题标题】:File uploading/Downloading samples in ASP.NET MVC2?ASP.NET MVC2 中的文件上传/下载示例?
【发布时间】:2011-05-11 20:46:11
【问题描述】:
我想知道关于 ASP.NET MVC2 的两件事,我从 Google 研究过但仍然感到困惑。希望我能在这里找到清晰明确的答案。
首先,如何使用自定义文件路径将文件上传到服务器。 (例如到 /Content/Files)
二、如何下载那个文件,既然url已经应用了URL Routing,那么如何映射到它们呢?
感谢您的回答!
【问题讨论】:
标签:
asp.net
asp.net-mvc-2
file
file-upload
download
【解决方案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();
}
至于下载,假设你有目录“~/Content/Files”...
您只需将它们排除在您的路线中即可。
routes.IgnoreRoute("Content/{*pathInfo}");