为上传的文件创建新文件夹 - Razor Engine

时间:2014-02-03 13:09:50

标签: asp.net razor asp.net-webpages

我在

上查看本教程

http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files

在这个主题上,我看到可以将各种文件发送到目标文件夹。

我的问题是,当用户发送一个或多个文件时,如何创建一个新目录?

@using Microsoft.Web.Helpers;
@{
  var message = "";
  if (IsPost) {
  var fileName = "";
  var fileSavePath = "";
  int numFiles = Request.Files.Count;
  int uploadedCount = 0;
  for(int i =0; i < numFiles; i++) {
      var uploadedFile = Request.Files[i];
      if (uploadedFile.ContentLength > 0) {
          fileName = Path.GetFileName(uploadedFile.FileName);
          fileSavePath = Server.MapPath("~/uploadedFiles/" + fileName);
          uploadedFile.SaveAs(fileSavePath);
          uploadedCount++;
      }
   }
   message = "File upload complete. Total files uploaded: " + uploadedCount.ToString();
   }
}
<!DOCTYPE html>
<html>
<head><title>FileUpload - Multiple File Example</title></head>
<body>
<form id="myForm" method="post"
   enctype="multipart/form-data"
   action="">
<div>
<h1>File Upload - Multiple-File Example</h1>
@if (!IsPost) {
    @FileUpload.GetHtml(
        initialNumberOfFiles:2,
        allowMoreFilesToBeAdded:true,
        includeFormTag:true,
        addText:"Add another file",
        uploadText:"Upload")
    }
<span>@message</span>
</div>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

在保存文件之前,创建所需的文件夹。 Directory.CreateDirectory将自动在指定路径中创建您的文件夹和任何其他非现有文件夹。创建目标文件夹后,只需将文件保存到该位置即可。

if (uploadedFile.ContentLength > 0) {
      fileName = Path.GetFileName(uploadedFile.FileName);

      string pathToSave = Server.MapPath("~/") + "/uploadedFiles/" + yourCustomFolderName;
      Directory.CreateDirectory(pathToSave);

      fileSavePath = pathToSave + fileName;

      uploadedFile.SaveAs(fileSavePath);
      uploadedCount++;
  }