0

I have a stream which contains signature image from my xamarin forms signature pad. I need to upload the image to server but I getting error:

FATAL UNHANDLED EXCEPTION: System.ObjectDisposedException: Cannot access a closed Stream

I am getting the exception in PostAsync line.

How can I access the stream?

public async void Upload(object sender, EventArgs e)
{
    signimgurl = await signature.GetImageStreamAsync(SignatureImageFormat.Png);

    image.HeightRequest = 250;

    image.Source = ImageSource.FromStream(() => 
    {
        return signimgurl;
    });

    var _content = new MultipartFormDataContent();

    _content.Add(new StreamContent(signimgurl),
        "\"file\"",
        $"\"{"testsign"}\"");

    var _httpClient = new HttpClient();
    var _uploadServiceBaseAdress = "http://myserver.rocket.com/api/Files/Upload";

    var httpResponesMessage = await _httpClient.PostAsync(_uploadServiceBaseAdress, _content);
    string _imgLocation = await httpResponesMessage.Content.ReadAsStringAsync();
}
vgru
  • 49,838
  • 16
  • 120
  • 201
batwing
  • 257
  • 1
  • 8
  • 22
  • Why is `signimgurl` a field, instead of a local variable? Are you calling this method from multiple threads at once? Btw prefixing local variables with `_` is quite the opposite of the coding conventions I've seen so far (but if it's your company's convention, then I guess it's not so big of an issue). – vgru Aug 21 '17 at 14:17
  • Please add the stacktrace. Of what type is signimgurl? – Fildor Aug 21 '17 at 14:25
  • 1
    I'm not familiar with GetImageStreamAsync. Does it return a byte array? Other issues I'm finding resolved it by creating a new memorystream in FromStream... FromStream(()=> new MemoryStream(signimgurlBytes) where signimgurlBytes is signimgurl or signimgurl converted, depending on its type and if it's already bytes or not. – Aaron Aug 21 '17 at 14:29
  • signimgurl is a stream – batwing Aug 21 '17 at 14:30
  • 5
    Just a suspicion: Could it be that `ImageSource.FromStream` closes the stream when it's done? Could you explicitly check that? – Fildor Aug 21 '17 at 14:31
  • as @Fildor says, the fact that you are using `signimgurl` two times looks like an error source as your error message is about re-using a closed stream. – Tewr Aug 21 '17 at 14:37
  • Reusing such a stream in a highly async environment is anyway not the best of ideas, I think. – Fildor Aug 21 '17 at 14:41
  • @Fildor yes. You are right. ImageSource.FromStream is the one closing the stream. Now can upload perfectly. – batwing Aug 21 '17 at 14:48
  • Glad I could point you to the solution. Maybe write your fix as an answer to your own question and accept it. Might be useful for other people with the same issue. – Fildor Aug 21 '17 at 15:06
  • Please take look - https://stackoverflow.com/questions/48164503/httpclient-multipart-form-data-post-image-and-json-same-time/48562888#48562888 – Anish Manchappillil Feb 01 '18 at 13:21

0 Answers0