将文件上载到MVC并将它们传输到WCF

时间:2013-11-21 15:47:59

标签: c# asp.net-mvc wcf asp.net-mvc-4

我目前正在尝试将大约6个文件上传到ASP.NET MVC。上传后,我需要将它们流式传输到WCF,让WCF将它们写入文件系统。

我还需要一种方法来处理文件大小。所有文件都将是图像,它们可能超过100MB,我不希望页面超时。

有人能指出我正确的方向去哪,或者如何开始。

这是我到目前为止的代码:

[HttpPost]
    public ActionResult Index(FileUpload file)
    {
        foreach (string upload in Request.Files)
        {                
            string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
            string filename = Path.GetFileName(Request.Files[upload].FileName);
            Request.Files[upload].SaveAs(Path.Combine(path, filename));
        }
        TempData["Status"] = "Your files were successfully upload.";
        return RedirectToAction("Index", "Employees");
    }

稍后我会添加一些东西来验证文件是否真的存在。提前致谢!

更新

在搞砸了一下之后,这就是我想出来的

foreach (var file in files)
        {
            if (file.ContentLength > 0)
            {
                FileUploadStream uploadedFile = null;

                uploadedFile.FileName = file.FileName;
                uploadedFile.StreamData = file.InputStream;
                uploadedFile.FileSize = file.ContentLength;

                BinaryReader b = new BinaryReader(file.InputStream);
                byte[] binData = b.ReadBytes(file.ContentLength);

                using (Proxy<IFileUpload> Proxy = new Proxy<IFileUpload>())
                {
                    uploadedFile = Proxy.Channel.SaveFiles(uploadedFile.FileName, binData);
                    Proxy.Close();
                }
            }
            else
            {
                TempData["Error"] = "Didn't work :(";
                return RedirectToAction("Index", "Employees");
            }
        }

        TempData["Status"] = "Holy crap, it worked :)";
        return RedirectToAction("Index", "Employees");

但是,当代码执行时,IEnumerable<HttpPostedFileBase> files为空。以下是我的观点:

    @model Common.Contracts.DataContracts.FileUploadStream

    @{
    ViewBag.Title = "Upload Tool";
}


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>IFileUpload</legend>
            PHOTO <input type="file" name="signUpload" />
            <br />
            <input type="submit" name="Submit" id="Submit" value="Upload Files" />
    </fieldset>
}

1 个答案:

答案 0 :(得分:0)

您可以查看ContentLength

for (int i = 0; i < this.Request.Files.Count; i++)
{
   var file = this.Request.Files[i];

   //
   // ContentLength comes in bytes, you must convert it to MB and then
   // compare with 100 MB
   //
   if(file.ContentLength / 1024 / 1024 > 100)
   {
      TempData["Status"] += file.FileName + " has It size greater than 100MB";
   }
   else
   {
     string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
     string filename = Path.GetFileName(file.FileName);
     file.SaveAs(Path.Combine(path, filename));
   }
}