09 June 2011

ASP.NET MVC - Store uploaded files

Here's how you can store uploaded files in ASP.NET MVC.
To work, the HTML file input control must be - and this is specific to HTML, not MVC - in a form that has it's enctype set to multipart/form-data.

public static void Store(HttpFileCollectionBase files,
                         EntityCollection list) {
  List attachments = new List();
  Attachment attachment = null;
  HttpPostedFileBase file = null;
  FileStream stream = null;
  string fullName = string.Empty;
  byte[] buffer = null;
  int length = 0;

  if (files != null && files.Count > 0) {
    foreach (string inputName in files) {
      if (!string.IsNullOrEmpty(inputName)) {
        file = files[inputName] as HttpPostedFileBase;
        if (file != null && !string.IsNullOrEmpty(file.FileName)) {
          //Generate file name
          fullName = Guid.NewGuid().ToString() + '-' + file.FileName;

          //Store the actual file
          using (stream = File.Create(
                 HttpContext.Current.Server.MapPath(
                 App.FOLDER_ATTACHMENTS + '/' + fullName))) {
            buffer = new byte[file.ContentLength];
            length = file.InputStream.Read(buffer, 0, file.ContentLength);
            stream.Write(buffer, 0, length);
          }

          //Create and attach to the entities
          attachment = new Attachment() {
            Name = fullName,
            Size = file.ContentLength
          };
          list.Add(attachment);
        }
      }
    }
  }
}

The files parameter above gets (HttpRequestBase)request.Files passed.
The function above will also associate the files with an entity, but that's another story.

No comments:

Post a Comment