【问题标题】:Handling HttpPostedFile in C#在 C# 中处理 HttpPostedFile
【发布时间】:2013-03-25 01:52:33
【问题描述】:

我有一个 C#.net Web 应用程序,可以(通过 POST 方法)将文件发送到另一个应用程序。在第二个应用程序中,我有以下代码来检索发布的文件。

HttpPostedFile hpf = Request.Files[0];

现在我可以通过代码保存文件了

hpf.SaveAs("The path to be saved");

但是我需要将它再次发送到另一个应用程序而不在这里保存(不保存在第二个应用程序中,我需要将它发送到第三个应用程序)。

(现在我可以做的是将文件保存在第二个应用程序中,然后通过提供与我在第一个应用程序中所做的路径完全相同的路径将其发布到第三个应用程序。但我需要另一个解决方案。)

我试过 hpf.fileName 但它只给出文件名(例如:test.txt)。当我像下面这样尝试时

string file = hpf.FileName;
string url = "the url to send file";
    using (var client = new WebClient())
    {
        byte[] result = client.UploadFile(url, file);
        string responseAsString = Encoding.Default.GetString(result);
    }

发生 WebException,例如“在 WebClient 请求期间发生异常。”

在 C# .net 中有什么方法可以做到吗?

【问题讨论】:

  • 您可以将文件转换为 byte[] 并修改服务以接受字节。
  • 如何将 hpf 转换为 byte[] 并修改服务以接受字节

标签: c# post web-applications webexception


【解决方案1】:

问题是,如果您不想使用上一个答案中建议的 Web 服务,则需要使用 HttpPostedFile 的 InputStream 属性。您应该使用 HttpWebRequest 对象来创建包含文件内容的请求。周围有很多帖子和教程,包括thisthis

【讨论】:

  • 我只有这个 HttpPostedFile hpf = Request.Files[0];在我的第二个应用程序中。如果不将文件保存在第二个应用程序中,我如何将其发布到第三个应用程序中?
  • 您应该阅读我的回答中有关链接的文章。这正是你所需要的。尤其是第二个 - this
【解决方案2】:

用于创建字节数组 How to create byte array from HttpPostedFile

这是一种在webservice中保存字节的方法

[WebMethod]
public string UploadFile(byte[] f, string fileName, string bcode)
{
    if (bcode.Length > 0)
    {
        try
        {
            string[] fullname = fileName.Split('.');
            string ext = fullname[1];
            if (ext.ToLower() == "jpg")
            {
                MemoryStream ms = new MemoryStream(f);
                FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath("~/bookimages/zip/") + bcode+"."+ext, FileMode.Create);
                ms.WriteTo(fs);
                ms.Close();
                fs.Close();
                fs.Dispose();


            }
            else
            {
                return "Invalid File Extention.";
            }
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }
    else
    {
        return "Invalid Bookcode";
    }

    return "Success";
}

【讨论】:

  • 抱歉,您可以忽略 bcode,因为我是从我的库中粘贴的。 byte[] f 是将 hpf 转换为 byte[] 时获得的 byte[] 。
  • 我会得到这样的流.. Stream inputStream = hpf.InputStream;我可以将此流转换为字节吗?
  • byte[] fileData = null;使用 (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) { fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength); } //fileData 是您将在第三个应用程序上发送到 web 服务的字节 []
  • 我的文件冒充代码如下 string url = "要发布的url";使用 (var client = new WebClient()) { byte[] result = client.UploadFile(url, file);字符串 responseAsString = Encoding.Default.GetString(result);我可以在这里对 Stream 对象做任何事情吗?
  • 对不起.. 似乎这段代码会将文件保存在应用程序中,或者它正在获取应用程序中已经存在的文件并发送它。不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 2011-01-26
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多