【问题标题】:How to post file from c# code in asp net mvc?如何在asp net mvc中从c#代码发布文件?
【发布时间】:2012-08-06 09:16:32
【问题描述】:

我有一个控制器方法,它以HttpPostedFileBase picture 作为参数。当然,它用于从表单加载图像。但现在我想使用该方法从另一种方法加载文件。我可以使用图像路径在代码中制作 HttpPostedFileBase 文件吗?或者可能是另一种解决方案是首选?

好的,代码:

public ActionResult UploadPicture(HttpPostedFileBase picture)
{
    if (picture.ContentLength > Convert.ToInt32(ConfigurationManager.AppSettings["MaxMBFileSize"]) * 1024 * 1024 || picture.ContentLength == 0)
    {
        return ClientError(ErrorCodes.ClientErrorCodes.FileSizeError, "File size is incorrect");
    }
    else
    {
        string contentType = picture.ContentType;

        if (!PictureHelper.ContentTypeIsValid(contentType))
        {
            return ClientError(ErrorCodes.ClientErrorCodes.MimeTypeError, "Incorrect file type");
        }
        else
        {
            string pictureName = Guid.NewGuid().ToString();
            pictureName += picture.FileName.Substring(picture.FileName.LastIndexOf('.'));

            string serverPath = AppDomain.CurrentDomain.BaseDirectory;
            picture.SaveAs(serverPath + ConfigurationManager.AppSettings["LocalImagesPath"] + pictureName);

            return Success(new { pictureName = pictureName });
        }
    }
}

真的,身体绝对不重要。当然我有类似的东西:

<form method="post" action="Photo\UploadPicture">
    <input type="file">
    <input type="submit" value="submit">
</form>

我想要类似的东西:

public ActionResult NewMethod()
{
    string path = ""; // real path to file here
    var file = OhMyGodMagicTransfer(path);
    // sending request
    request.attach(file);
    request.send;
}

【问题讨论】:

  • 你说你有一个方法,你想重用它。我会说答案可能是“当然,为什么不呢?代码重用是一件好事!”但是您没有发布有关该方法的详细信息,它是如何使用的,以及该方法实际做了什么,所以不可能说。
  • 当用户使用表单发布文件时,它会通过 HttpPostedFileBase 参数发布到第一个方法。这很明显。我想在第二种方法中做同样的事情,因为使用了表单。调用第一个方法或给出一些简单的参数非常简单,但我想知道如何给出文件参数。创建 HttpPostedFileBase 对象可能是解决方案,但我不知道它是否真实
  • 这对您来说可能很明显,但对于我们这些看不到您的代码的阅读者来说,没有什么是显而易见的。 “文件参数”是什么意思? “这是真的吗?”是什么意思?

标签: c# asp.net-mvc post httppostedfilebase


【解决方案1】:

如果文件已经保存到磁盘,那么只返回一个 FilePathResult :

 public ActionResult FileDownload()
        {
            var fileLocation = "C:\file.jpg"; 
            var fileType = "image/jpeg" //this is the Mime content type;
            return File(fileLocation , fileType ); 
        }

查看 File 的重载,因为您可以返回文件流或字节数组。

【讨论】:

  • 第一种方法怎么用? HttpPostedFileBase 图片 = File(fileLocation, "application/pdf");不工作
  • 刚刚编辑了答案。在您的情况下,只需使用行'return File(path, "image/jpg");' .假设文件是​​ jpg 文件或只是将文件类型编辑为适当的 Mime 类型webmaster-toolkit.com/mime-types.shtml
  • "return" 与此案无关。我需要将我的文件发送到其他网址。在这里返回哪个连接?
  • 不确定我是否理解你,但我的答案中的 url 将是 /FileDownload (取决于你的路由)并且从浏览器请求这个 url 将下载文件。
  • 我不需要在浏览器中打开任何东西,它只是代码......我有 ApiMethod 类,它有字段“body,我需要在其中编写类似“{ picture = null, smthelse = 123" }。代码测试此方法,将正文发送到某个 url。控制器方法,发送到哪个请求有一些参数,这里是 HttpPostedFileBase 图片和 int smthelse。我需要将非空值放入该正文。真实图像
【解决方案2】:

   public ActionResult Index()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\proba\MvcApplication3\MvcApplication3\XMLFile1.xml");
            List<Class1> pitanja = new List<Class1>();
            Random rand = new Random();
            int broj1 = rand.Next(1, 3);
            int broj2 = rand.Next(3, 5);
            int broj3 = 5;

            TempData["odg1"] = broj1;
            TempData["odg2"] = broj2;
            TempData["odg3"] = broj3;

            string odg1 = Request.Form["odgg1"];
            string odg2 = Request.Form["odgg2"];
            string odg3 = Request.Form["odgg3"];

            TempData["korisodg1"] = odg1;
            TempData["korisodg2"] = odg2;
            TempData["korisodg3"] = odg3;


            foreach (XmlNode cvor in doc.SelectNodes("/kviz/Pitanje"))
            {

                if (broj1.ToString() == cvor["Rbr"].InnerText)
                {
                    pitanja.Add(
                        new Class1
                        {
                            pitanje = cvor["Pitanje"].InnerText,
                            odg1 = cvor["Odgovor1"].InnerText,
                            odg2 = cvor["Odgovor2"].InnerText,
                            odg3 = cvor["Odgovor3"].InnerText,
                            odg4 = cvor["Odgovor4"].InnerText,
                            resenje = cvor["Resenje"].InnerText
                        }
                        );
                }
                else if (broj2.ToString() == cvor["Rbr"].InnerText)
                {
                    pitanja.Add(
                        new Class1
                        {
                            pitanje = cvor["Pitanje"].InnerText,
                            odg1 = cvor["Odgovor1"].InnerText,
                            odg2 = cvor["Odgovor2"].InnerText,
                            odg3 = cvor["Odgovor3"].InnerText,
                            odg4 = cvor["Odgovor4"].InnerText,
                            resenje = cvor["Resenje"].InnerText
                        }
                        );
                }
                else if (broj3.ToString() == cvor["Rbr"].InnerText)
                {
                    pitanja.Add(
                        new Class1
                        {
                            pitanje = cvor["Pitanje"].InnerText,
                            odg1 = cvor["Odgovor1"].InnerText,
                            odg2 = cvor["Odgovor2"].InnerText,
                            odg3 = cvor["Odgovor3"].InnerText,
                            odg4 = cvor["Odgovor4"].InnerText,
                            resenje = cvor["Resenje"].InnerText
                        }
                        );
                }

            }
            return View(pitanja);

        }

        public ActionResult operater()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\proba\MvcApplication3\MvcApplication3\XMLFile1.xml");
            List<Class1> pitanja = new List<Class1>();

            foreach (XmlNode cvor in doc.SelectNodes("/kviz/Pitanje"))
            {
                if (TempData["odg1"].ToString() == cvor["Rbr"].InnerText)
                    pitanja.Add(new Class1
                    {
                        resenje = cvor["Resenje"].InnerText,
                        pitanje = cvor["Pitanje"].InnerText,
                        odgKorisnika = TempData["korisodg1"].ToString()
                    });

                else if (TempData["odg2"].ToString() == cvor["Rbr"].InnerText)
                    pitanja.Add(new Class1
                    {
                        resenje = cvor["Resenje"].InnerText,
                        pitanje = cvor["Pitanje"].InnerText,
                        odgKorisnika = TempData["korisodg2"].ToString()
                    });
                else if (TempData["odg3"].ToString() == cvor["Rbr"].InnerText)
                    pitanja.Add(new Class1
                    {
                        resenje = cvor["Resenje"].InnerText,
                        pitanje = cvor["Pitanje"].InnerText,
                        odgKorisnika = TempData["korisodg3"].ToString()
                    });
            }

            return View(pitanja);
        }

    }
}
@*@{
    ViewBag.Title = "Index";
    }
@Html.ActionLink("Operater", "operater", "home")
@Html.ActionLink("Nova pitanja","index","home")
@using(Html.BeginForm("Index","home")){
    
<h2>Index</h2>

    foreach (MvcApplication3.Models.Class1 pitanje in Model)
{
    
    @pitanje.pitanje;
    <br />
    @pitanje.odg1;<br />
    @pitanje.odg2;<br />
    @pitanje.odg3;<br />
    @pitanje.odg4;<br />
    <hr />
}
<input type="text" name="odgg1"  /><br />
<input type="text" name="odgg2" /><br />
<input type="text" name="odgg3" /><br />
<input type="submit" value ="Potvrdi" />
}*@
@*@{
    ViewBag.Title = "operater";
}
@Html.ActionLink("Nova pitanja","index","home")

<h2>operater</h2>

@foreach (MvcApplication3.Models.Class1 pitanj in Model)
{
    @pitanj.pitanje;<br /> 
    @pitanj.resenje;<br /><br /><br />
    @pitanj.odgKorisnika;
    <hr />
}*@

【讨论】:

  • 感谢您分享您的代码示例。如果您可以在其中添加一些 cmets 来解释该过程,那将非常有帮助。谢谢。
猜你喜欢
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
相关资源
最近更新 更多