4

I'm writing a C# ASP.Net application for client to post files to other server. I'm using a generic handler to handle posted files from client to server. But in my handler, context.Request.Files always empty (0 count). I believe my post method is right, because when I tried to move the handler in the same domain as the client, I can accept the files and save them. But the problem is I need to save the files to the other server.

Here is the code to post files:

    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;

    }

And here is the code behind my handler to receive the files:

    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
        }
    }
RBT
  • 24,161
  • 21
  • 159
  • 240
Gus Yan To
  • 53
  • 1
  • 6
  • Didn't get why you setting content type on receiving side, but not in sending side. – VikciaR Jul 18 '13 at 10:26
  • http://stackoverflow.com/questions/6718664/is-it-possible-to-perform-an-asynchronous-cross-domain-file-upload – VikciaR Jul 18 '13 at 10:27
  • I actually set the content type on sending side too. On my handler, it's just for testing purpose only. With or without that line, the problem still exists. – Gus Yan To Jul 18 '13 at 10:31
  • 1
    Did you get a solution for that? My context.Request.Files.Count is always 0 – G43beli Feb 01 '17 at 09:53

1 Answers1

0
   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;
        }
    }
  • Try this is web api example its works for me.Here i am handle multiple files in one request (multipart request) and save file in local folder. – navjyot verma Nov 23 '13 at 18:25
  • please add some explaining to the orginal answer. See http://msmvps.com/blogs/jon_skeet/archive/2009/02/17/answering-technical-questions-helpfully.aspx and http://stackoverflow.com/questions/how-to-answer – Florian Nov 23 '13 at 18:42
  • @navjyotverma `Operator ?? cannot be applied to operands of type 'HttpRequestMessage' and 'HttpRequestBase'`. And you can't assign `Request` to `request` - different types, one is the Message, the other is the Request. You also can't take a `Response` - there's no available type for that. Did you import some weird assembly or namespace to get all this to work? – vapcguy Mar 27 '18 at 22:12
  • @navjyotverma I had to do `HttpContextWrapper objwrapper = (HttpContextWrapper)Request.RequestContext.HttpContext;` just to get the proper HttpContext, and had to make the path `string path = Server.MapPath("~/Uploads");` instead of that `PhysicalApplicationPath` stuff, just to get it to compile. Never got a `collection.Count` > 0, though. – vapcguy Mar 27 '18 at 22:52