简体   繁体   English

从请求中提取文件

[英]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. 我正在使用ASP.net MVC5。下面的代码可用于存储文件,但是我需要存储请求或提取从请求中上传的文件,以便可以在上传之前将文件传递给另一个类中的方法以进行验证。到文件服务器。 I noticed below that Request.Files[upload].SaveAs contains the files, but how do I pass the file to another class? 我在下面注意到Request.Files [upload] .SaveAs包含文件,但是如何将文件传递给另一个类? I tried passing the HttpPostedFileBase File to another class, but it doesn't recognize Files. 我尝试将HttpPostedFileBase File传递给另一个类,但无法识别文件。

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");
    }

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 . 您的Request.Files还应该具有InputStream Use that to copy the file to a Byte[] buffer, and go from there. 使用该文件将文件复制到Byte []缓冲区,然后从那里去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM