Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

How do I receive an image POST (XHR) via ASP.NET?

I am playing around with the xhr demo to upload an image and it's returning a 200 status from my server, but for the life of me, I can't figure out how to capture the image on the server.

Has anyone ever done this with .NET? If so, can you please post a code snippet, or point me in the right direction?

Thanks!

.: Adam

— asked September 8th 2010 by Adam Callen
  • .net
  • asp
  • asp.net
  • receive
  • request
  • xhr
1 Comment
  • Bump, stuck here too…

    — commented April 17th 2011 by Rahul Dhingra

3 Answers

  • Adam,
    I have the solution that works in .NET.
    Let me know if this would work for you.
    Ilya Gorelik

    Android code:

    function SubmitImage(reqID) {
    
        var image = imageView.toBlob();
        var image_name = reqID + '.png';
        Ti.API.info('imageName: ' + image_name );
    
        var xhr = Titanium.Network.createHTTPClient();
    
        xhr.onerror = function(e) {
            Ti.API.info('IN ERROR ' + e.error);
            actInd.hide();
        };
        xhr.onload = function() {
            //alert("Your Request has been submitted!");
            Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
            actInd.hide();
        };
    
        // open the client
        xhr.open('POST', 'http://<server_name_or_ip>/<webservice_name>.asmx/UploadFileCollection');
        xhr.send({ media: image, image_name: image_name });
    
    }
    

    .NET code:
    You need to create a webservice and add this function:

    <WebMethod(Description:="Upload a file from a POSTed web form.")> _
        Public Function UploadFileCollection() As System.Data.DataSet
            Dim fileName As String = ""
            Dim vFileType As String = ""
            Dim vFileExt As String = ".png"
            Dim metaBuffer As String = ""
            Dim aDate As DateTime = DateTime.Now
            Dim metaname As String = aDate.Ticks.ToString()
            Dim vContentType As String
    
            Try
                'HTTP Context to get access to the submitted data
                Dim postedContext As HttpContext = HttpContext.Current
    
                'File Collection that was submitted with posted data
                Dim Files As HttpFileCollection = postedContext.Request.Files
    
                fileName = "upload_image_" & metaname
    
                If Files.Count = 1 AndAlso Files(0).ContentLength > 1 AndAlso fileName         IsNot Nothing AndAlso fileName <> "" Then
    
                    'The byte array we'll use to write the file with
                    Dim binaryWriteArray As Byte() = New Byte(Files(0).InputStream.Length - 1) {}
    
                    'Read in the file from the InputStream
                    Files(0).InputStream.Read(binaryWriteArray, 0, CInt(Files(0).InputStream.Length))
    
                    vContentType = Files(0).ContentType
    
                    'Open the file stream
                    Dim objfilestream As New System.IO.FileStream("c:\temp\upload\" & fileName & vFileExt, FileMode.Create, FileAccess.ReadWrite)
    
                    'Write the file and close it
                    objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length)
                    objfilestream.Close()
    
             Return "success: " & filename
                Else
                    Return "failed "
                End If
            Catch ex1 As Exception
                Throw New Exception("Problem uploading file: " & ex1.Message & " f: " & fileName)
            End Try
        End Function
    
    — answered September 6th 2011 by Ilya Gorelik
    permalink
    2 Comments
    • Hi Ilya,

      I can see how your example might work but it doesn't.. The file collection is 0 for me, I also need to return a string not a dataset..

      I'm wondering how to do this with a file, I essentially want to do:

      xhr.send({ media: file.read(), file_name: myFilename });
      

      — commented August 24th 2012 by Mark Henderson
    • Mark,
      Can you try this code. See if this "postedContext.Request("file_name")" has a value you are passing to the webservice. It should work. I am using this exact code currently in production.
      Also, try loading the image outside of the call to xhr.send

      var img = file.read();
      xhr.send( { media: img, file_name: myFilename });
      

      Let me know if this works.
      Ilya.

        <WebMethod(Description:="Upload a file from a POSTed web form. Include the value - fileName ")> _
        Public Function UploadFileCollection() As String
          Dim fileName As String = ""
          Dim vFileType As String = ""
          'Dim vFileExt As String = ".jpg"
          Dim metaBuffer As String = ""
          Dim aDate As DateTime = DateTime.Now
          Dim metaname As String = aDate.Ticks.ToString()
          Dim vContentType As String
      
      
          Try
            'HTTP Context to get access to the submitted data
            Dim postedContext As HttpContext = HttpContext.Current
      
            'File Collection that was submitted with posted data
            Dim Files As HttpFileCollection = postedContext.Request.Files
      
            fileName = postedContext.Request("file_name")
      
            If Files.Count = 1 AndAlso Files(0).ContentLength > 1 AndAlso fileName IsNot Nothing AndAlso fileName <> "" Then
      
              'The byte array we'll use to write the file with
              Dim binaryWriteArray As Byte() = New Byte(Files(0).InputStream.Length - 1) {}
      
              'Read in the file from the InputStream
              Files(0).InputStream.Read(binaryWriteArray, 0, CInt(Files(0).InputStream.Length))
      
              vContentType = Files(0).ContentType
      
              'Open the file stream
              Dim objfilestream As New System.IO.FileStream(Server.MapPath("\") & fileName, FileMode.Create, FileAccess.ReadWrite)
      
              'Write the file and close it
              objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length)
      
              objfilestream.Close()
      
              Return "success:" 
            Else
              Return "failure:"
            End If
          Catch ex1 As Exception
          Return "error:"
          End Try
        End Function
      

      — commented August 24th 2012 by Ilya Gorelik
  • C# version -

    [WebMethod(Description = "Upload a file from a POSTed web form.")]
    public System.Data.DataSet UploadFileCollection()
    {
        string fileName = "";
        string vFileType = "";
        string vFileExt = ".png";
        string metaBuffer = "";
        DateTime aDate = DateTime.Now;
        string metaname = aDate.Ticks.ToString();
        string vContentType = null;
    
        try {
            //HTTP Context to get access to the submitted data
            HttpContext postedContext = HttpContext.Current;
    
            //File Collection that was submitted with posted data
            HttpFileCollection Files = postedContext.Request.Files;
    
            fileName = "upload_image_" + metaname;
    
            if (Files.Count == 1 && Files(0).ContentLength > 1 && fileName != null && !string.IsNullOrEmpty(fileName)) {
    
                //The byte array we'll use to write the file with
                byte[] binaryWriteArray = new byte[Files(0).InputStream.Length];
    
                //Read in the file from the InputStream
                Files(0).InputStream.Read(binaryWriteArray, 0, Convert.ToInt32(Files(0).InputStream.Length));
    
                vContentType = Files(0).ContentType;
    
                //Open the file stream
                System.IO.FileStream objfilestream = new System.IO.FileStream("c:\\temp\\upload\\" + fileName + vFileExt, FileMode.Create, FileAccess.ReadWrite);
    
                //Write the file and close it
                objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length);
                objfilestream.Close();
    
                return "success: " + filename;
            } else {
                return "failed ";
            }
        } catch (Exception ex1) {
            throw new Exception("Problem uploading file: " + ex1.Message + " f: " + fileName);
        }
    }
    
    — answered February 19th 2013 by Cesar Aviles
    permalink
    1 Comment
    • view code below

      — commented February 20th 2013 by Cesar Aviles
  • //clean up C# conversion
     [WebMethod(Description = "Upload a file from a POSTed web form.")]
        public string UploadFileCollection()
        {
            string fileName = "";
            string vFileType = "";
            string vFileExt = ".png";
            string metaBuffer = "";
            DateTime aDate = DateTime.Now;
            string metaname = aDate.Ticks.ToString();
            string vContentType = null;
    
            try
            {
                //HTTP Context to get access to the submitted data
                HttpContext postedContext = HttpContext.Current;
    
                //File Collection that was submitted with posted data
                HttpFileCollection Files = postedContext.Request.Files;
    
                fileName = "upload_image_" + metaname;
    
                if (Files.Count == 1 && Files[0].ContentLength > 1 && fileName != null && !string.IsNullOrEmpty(fileName))
                {
    
                    //The byte array we'll use to write the file with
                    byte[] binaryWriteArray = new byte[Files[0].InputStream.Length];
    
                    //Read in the file from the InputStream
                    Files[0].InputStream.Read(binaryWriteArray, 0, Convert.ToInt32(Files[0].InputStream.Length));
    
                    vContentType = Files[0].ContentType;
    
                    //Open the file stream
                    System.IO.FileStream objfilestream = new System.IO.FileStream("c:\\temp\\upload\\" + fileName + vFileExt, FileMode.Create, FileAccess.ReadWrite);
    
                    //Write the file and close it
                    objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length);
                    objfilestream.Close();
    
                    return "success: " + fileName;
                }
                else
                {
                    return "failed ";
                }
            }
            catch (Exception ex1)
            {
                throw new Exception("Problem uploading file: " + ex1.Message + " f: " + fileName);
            }
        }
    
    — answered February 20th 2013 by Cesar Aviles
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.