Nibbler
Nibbler

Reputation: 334

Create new folder for uploaded files - Razor Engine

I was checking this tutorial on

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

On this topic i saw that is possible to send various files to a destination folder.

My question is, how can i make a new directory when the user sends a file or more 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>

Upvotes: 0

Views: 1406

Answers (1)

Andrei V
Andrei V

Reputation: 7506

Just before saving the file, create the folder that you want. Directory.CreateDirectory will automatically create your folder and any other non existing folders in the specified path. After creating your target folder, just save the file to that location.

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++;
  }

Upvotes: 2

Related Questions