c# - ASP.Net 处理程序 Request.Files 始终为空

标签 c# .net file upload handler

我正在为客户端编写一个 C# ASP.Net 应用程序以将文件发布到其他服务器。我正在使用通用处理程序来处理从客户端到服务器的已发布文件。但在我的处理程序中,context.Request.Files 始终为空(0 计数)。我相信我的 post 方法是正确的,因为当我尝试将处理程序移动到与客户端相同的域中时,我可以接受文件并保存它们。但问题是我需要将文件保存到其他服务器。

这是发布文件的代码:

    private void UploadFilesToRemoteUrl3(HttpFileCollection files)
    {
        string url = "http://localhost:19107/Catalog/api/dashboard/ImageHandler.ashx";
        long length = 0;
        string boundary = "----------------------------" +
        DateTime.Now.Ticks.ToString("x");
        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.KeepAlive = true;

        httpWebRequest2.Credentials =
        System.Net.CredentialCache.DefaultCredentials;

        Stream memStream = new System.IO.MemoryStream();

        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
        memStream.Write(boundarybytes,0,boundarybytes.Length);
        length += boundarybytes.Length;

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

        foreach (string s in files)
        {
            HttpPostedFile file = files[s];

            string header = string.Format(headerTemplate, "file", file.FileName);

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            memStream.Write(headerbytes,0,headerbytes.Length);
            length += headerbytes.Length;

            byte[] buffer = new byte[1024];

            int bytesRead = 0;

            while ( (bytesRead = file.InputStream.Read(buffer, 0, buffer.Length)) != 0 )
            {
                memStream.Write(buffer, 0, bytesRead);
                length += bytesRead;
            }

            memStream.Write(boundarybytes,0,boundarybytes.Length);
            length += boundarybytes.Length;

            file.InputStream.Close();
        }

        httpWebRequest2.ContentLength = memStream.Length;

        Stream requestStream = httpWebRequest2.GetRequestStream();

        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer,0,tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer,0,tempBuffer.Length );
        requestStream.Close();
        WebResponse webResponse2 = httpWebRequest2.GetResponse();

        Stream stream2 = webResponse2.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);
        string a = reader2.ReadToEnd();
        webResponse2.Close();
        httpWebRequest2 = null;
        webResponse2 = null;

    }

下面是我的处理程序接收文件的代码:

    public void ProcessRequest(HttpContext context)
    {
        context.Request.ContentType = "multipart/form-data";
        int count = context.Request.Files.Count; //always 0
        foreach (string s in context.Request.Files)
        {
            string response = "";
            HttpPostedFile file = context.Request.Files[s];

            //code to save files
        }
    }

最佳答案

   public Response<List<string>> UplaoadPostImage()
    {
        Response<List<string>> response = new Response<List<string>>();
        ResponseImage objtemp = new ResponseImage();
        List<string> objlist = new List<string>();
        try
        {
            HttpContextWrapper objwrapper = GetHttpContext(this.Request);
            HttpFileCollectionBase collection = objwrapper.Request.Files;
            if (collection.Count > 0)
            {
                foreach (string file in collection)
                {

                    HttpPostedFileBase file1 = collection.Get(file);
                    Stream requestStream = file1.InputStream;
                    Image img = System.Drawing.Image.FromStream(requestStream);
                    //Image UserImage = objcommon.ResizeImage(img, 600, 600);
                    string UniqueFileName = file1.FileName;
                    img.Save(HttpContext.Current.Request.PhysicalApplicationPath + "UploadImage\\" + UniqueFileName, System.Drawing.Imaging.ImageFormat.Png);
                    objlist.Add(ConfigurationManager.AppSettings["ImagePath"] + UniqueFileName);
                    requestStream.Close();
                }
                response.Create(true, 0, Messages.FormatMessage(Messages.UploadImage_Sucess, ""), objlist);
            }
            else
            {
                response.Create(false, 0, "File not found.", objlist);
            }
        }
        catch (Exception ex)
        {
            response.Create(false, -1, Messages.FormatMessage(ex.Message), objlist);
        }

        return response;
    }

    private HttpContextWrapper GetHttpContext(HttpRequestMessage request = null)
    {
        request = request ?? Request;

        if (request.Properties.ContainsKey("MS_HttpContext"))
        {
            return ((HttpContextWrapper)request.Properties["MS_HttpContext"]);
        }
        else if (HttpContext.Current != null)
        {
            return new HttpContextWrapper(HttpContext.Current);
        }
        else
        {
            return null;
        }
    }

关于c# - ASP.Net 处理程序 Request.Files 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17720748/

相关文章:

c# - 获取特定类型的所有控件

c# - 为什么编译后代码注入(inject)比预编译代码注入(inject)更好?

C TCP套接字无法接收文件

java - 文件读取 : Getting partial Output

c# - LINQ 在具有空格分隔值的列表中搜索

c# - 我如何优先考虑 WPF 文本框自动换行?

asp.net - 您必须添加对程序集“netstandard,Version=2.0.0.0”的引用

C# Foreach XML 节点

c# - 使用 Unity 注入(inject)构造函数参数

java - 下载的文件有 0 字节