ConfusedDeer
ConfusedDeer

Reputation: 3415

extracting files from request

I'm using ASP.net MVC 5. The code below works to store files, but I need to store the request or extract the files uploaded from the request so I can pass the file to a method in another class for validation BEFORE I upload to the file server. I noticed below that Request.Files[upload].SaveAs contains the files, but how do I pass the file to another class? I tried passing the HttpPostedFileBase File to another class, but it doesn't recognize Files.

In my view:

 @using (Html.BeginForm("FileUpload",
                          "Upload", 
                          FormMethod.Post,
                          new { enctype = "multipart/form-data" }))

  { <label for="file">Upload Image:</label> 
         <input type="file" name="FileUpload" /><br />
         <input type="submit" name="Submit" id="Submit" value="Upload" />

 }

My Controller:

 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        //HttpPostedFileBase request = file; 
        foreach (string upload in Request.Files)
        {

          System.Diagnostics.Debug.WriteLine("*********************savepath:" + Request.Files[upload].FileName+"********************");

            string savePath = "C:\desktop";
            string newPathForFile = Path.Combine(savePath, Path.GetFileName(Request.Files[upload].FileName));
            Request.Files[upload].SaveAs(Path.Combine(savePath, newPathForFile));
        }

        return View("Home");
    }

Upvotes: 0

Views: 645

Answers (1)

jeffrapp
jeffrapp

Reputation: 58

You can't really pass the "file," since at this point there really isn't a file. We're really looking at a bunch of bytes. Your Request.Files should also have an InputStream. Use that to copy the file to a Byte[] buffer, and go from there.

Upvotes: 1

Related Questions