Android Question Upload a image file (jpg) on a C# WebService

Antonio Ferreira

Member
Licensed User
Longtime User
I

I have a error on Upload a image file (jpg) on an C# WebService


the code:


Dim in As InputStream
in=File.OpenInput(MyFolder,My_image)
Dim out As OutputStream
out.InitializeToBytesArray(1000)
File.Copy2(in, out)
Dim data() As Byte
data = out.ToBytesArray


Dim m As Map
m.Initialize
m.Put("DocumentName",My_image_name)
m.Put("DocumentContent",data)
m.Put("DocumentType","IMAGE")

Dim JSONG As JSONGenerator
JSONG.Initialize(m)
MJSON=JSONG.ToString
LOG(MJSON)
InsertBytes(Starter.Xservice & "/odata/cf_imalink/UploadDocument", MJSON.GetBytes("UTF8"),Mjob)

Public Sub InsertBytes(Link As String, data() As Byte, jobName As String)
Dim Job As HttpJob
Job.Initialize(jobName, Me)
Job.PostBytesJSON(Link,data)
Job.GetRequest.SetHeader("Authorization",Starter.Xspass)
End Sub


My Map value for "DocumentContent" key on LOG(MJSON) is:

"DocumentContent": [-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,3,-6,0,0,2,77,8,6,0,0,0,-127, . . .

But the correct "format" for "DocumentContent" value in a C# webservice by another aplication map is:
(without error)

"DocumentContent": "LypDb3JyaWdpciBkdXBsaWNhZG9zIGVNYW51dCAqLw0KDQpkZWxc2VsZWN0ICogZ . . .



Any light will be very appreciated

Thanks

A. Ferreira
 

Ohanian

Active Member
Licensed User
Longtime User
Hi,

Here's a sample (on both sides)

App :
B4X:
Dim myJob As HttpJob                   
        myJob.Initialize("PostImage", Me)   
        myJob.PostFile(Main.sWebServiceURL & "webservice.asmx/ProfileUploader", File.DirRootExternal, "profile.jpg")

WS :
B4X:
[WebMethod()]
        public string ProfileUploader()
        {
            try
            {
                string fileName = Guid.NewGuid().ToString().ToLower();

                int length = Convert.ToInt32(Context.Request.InputStream.Length);
                byte[] buffer = new byte[length];
                Context.Request.InputStream.Read(buffer, 0, length);

                MemoryStream ms = new MemoryStream(buffer);

                GenerateThumbnails(1, ms, System.Web.Hosting.HostingEnvironment.MapPath("~/ImageStorage/") + fileName);

                ms.Close();

                JavaScriptSerializer js = new JavaScriptSerializer();

                Context.Response.Expires = -1;
                Context.Response.ContentType = "application/json";

                Context.Response.Write(js.Serialize(fileName));

                try
                {
                    Context.Response.End();
                    return string.Empty;
                }
                catch (System.Threading.ThreadAbortException ex1)
                {
                    return string.Empty;
                }

            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
 
Upvote 0

swabygw

Active Member
Licensed User
Longtime User
I know this thread is old, but have a question on this - I have the following code in B4A to upload a picture taken with the smartphone camera to the server:

B4X:
Dim j As HttpJob
j.Initialize("PostImage", Me)
j.PostFile("http://" & Starter.IPAddr & "/imgupload.asmx", Dir, OrigFileName)
And the following in the file imgupload.asmx on the server:
B4X:
Dim length As Integer = Convert.ToInt32(Context.Request.InputStream.Length)
Dim buffer() As Byte = New Byte((length) - 1) {}
Context.Request.InputStream.Read(buffer, 0, length)
Dim ms As MemoryStream = New MemoryStream(buffer)

Dim file As New FileStream("test.jpg", FileMode.Create, FileAccess.Write)
ms.WriteTo(file)
file.Close()

ms.Close

Dim js As JavaScriptSerializer = New JavaScriptSerializer
Context.Response.Expires = -1
Context.Response.ContentType = "application/json"
Context.Response.Write(js.Serialize("test response"))

Context.Response.End
But this is returning "Internal Server Error". Does anything pop out as incorrect? Any ideas on how to debug this?
P.S., I'm testing this on my localhost IIS server on my PC.

Here's the error stack:
sending message to waiting queue (OnActivityResult)
running waiting messages (1)
** Activity (profileedit) Resume **
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="soap:Receiverhttp://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.Xml.XmlException: Invalid character in the given encoding. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.InvalidCharRecovery(Int32&amp; bytesCount, Int32&amp; charsCount)
at System.Xml.XmlTextReaderImpl.GetChars(Int32 maxCharsCount)
at System.Xml.XmlTextReaderImpl.ReadData()
at System.Xml.XmlTextReaderImpl.SwitchEncoding(Encoding newEncoding)
at System.Xml.XmlTextReaderImpl.ParseXmlDeclaration(Boolean isTextDecl)
at System.Xml.XmlTextReaderImpl.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing)
--- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>
JobDone(PostImage):false
Internal Server Error
 
Upvote 0

swabygw

Active Member
Licensed User
Longtime User
I got past this hurdle, but encountered a new issue. To get to the next step, though, changed three things:
1) Changed request to:
B4X:
Dim fd As FileData
fd.Initialize
fd.Dir = Dir
fd.FileName = OrigFileName
fd.KeyName = "files"
fd.ContentType = "application/octet-stream"
files.Add(fd)
Dim NV As Map
NV.Initialize
NV.Put("note1", "abc")
Dim req As OkHttpRequest
req = MultipartPost.CreatePostRequest("http://" & Starter.IPAddr & "/imgupload.aspx", NV, files)
hc.Execute(req, 1)
2) And changed...
B4X:
Dim file As New FileStream("test.jpg", FileMode.Create, FileAccess.Write)
...
Context.Response.End
to
B4X:
Dim file As New FileStream(Server.MapPath("test.jpg"), FileMode.Create, FileAccess.Write)
...
Context.Response.OutputStream.Close
3) And had to change the permissions on the folder it's writing to...essentially, gave IUSR, IIS_IUSRS, NETWORK SERVICE full control of the root folder and subfolders.

A file named "test.jpg" of size 18kb now shows up, but trying to open the file (with MSPaint or Windows Viewer) fails saying the file is empty or corrupted.
 
Last edited:
Upvote 0
Top