0

I am trying to upload files from the Xamarin mobile app using Web Service. But after Pick File I could not send the file to the web service. I suppose the web service is located at the following address: www.haythamweb.com/myServices.asmx/uploadfiles.

I have two parameters: byte[] fileContent, string fileName

This is the code for the web service:

[WebMethod]
public string UploadFile(byte[] fileContent, string fileName)
{
    try
    {
        MemoryStream ms = new MemoryStream(fileContent);
        FileStream fs = new FileStream
        (System.Web.Hosting.HostingEnvironment.MapPath
        ("~/TransientStorage/") +
        fileName, FileMode.Create);
        ms.WriteTo(fs);
        ms.Close();
        fs.Close();
        fs.Dispose();
        return "OK";
    }
    catch (Exception ex)
    {
        // return the error message if the operation fails
        return ex.Message.ToString();
    }
}

This is the code for the upload button I could not complete:

private async void Button_Clicked(object sender, EventArgs e)
{
    var file = await CrossFilePicker.Current.PickFile();

    if (file != null)
    {
        lbl.Text = file.FileName ;
    }

    String URI = "http://haythamweb.com/myServices.asmx/uploadfiles";
       ...........................
       ...........................
       ...........................
       ...........................
    }
}

Could you please help me. Thank you.

Jan Nepraš
  • 794
  • 1
  • 7
  • 29
Haytham
  • 1
  • 2
  • there are thousands of existing posts, articles, tutorials, and sample apps that demonstrate uploading to a webservice in C# - have you tried anything? – Jason May 20 '20 at 11:41
  • Yes, I tried some, but it didn't work out I am also new to using Xamarin – Haytham May 20 '20 at 18:14
  • then show us what you tried and explain what problems you encountered – Jason May 20 '20 at 18:53
  • i tried this: var bytes = filedata.DataArray; HttpClient client = new HttpClient(); MultipartFormDataContent content = new MultipartFormDataContent(); ByteArrayContent bContent = new ByteArrayContent(bytes); StringContent fileNameContent = new StringContent(filedata.FileName); content.Add(bContent, "fileContent", filedata.FileName); content.Add(fileNameContent, "fileName"); var response = await client.PostAsync(URI, content); – Haytham May 21 '20 at 08:22
  • I got the following error: {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Cache-Control: private Date: Thu, 21 May 2020 07:21:31 GMT Server: Microsoft-IIS/10.0 X-Android-Received-Millis: 1590045690540 X-Android-Response-Source: NETWORK 500 X-Android-Selected-Protocol: http/1.1 X-Android-Sent-Millis: 1590045690240 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 50 Content-Type: text/plain; charset=utf-8 }} – Haytham May 21 '20 at 08:22
  • You could install the plugin https://github.com/CrossGeeks/FileUploaderPlugin from nuget . – Lucas Zhang May 21 '20 at 14:17
  • 500 is a server error, what do your logs show? – Jason May 21 '20 at 15:27

1 Answers1

0
      //We will use FilePicker to upload image in Xamarin forms
      
      // **Page.xaml** 
      
      
         <StackLayout HeightRequest="80" HorizontalOptions="Start" 
          VerticalOptions="Start" Orientation="Horizontal">
                        <Frame Padding="0" HorizontalOptions="Start" 
         Margin="10,0,0,0" VerticalOptions="CenterAndExpand" 
        CornerRadius="50" BorderColor="White" HeightRequest="50" 
    WidthRequest="50" >
                            <Image x:Name="UploadImage_pic" 
  Aspect="AspectFill" HeightRequest="50" WidthRequest="50"/>
                        </Frame>
                        <StackLayout Orientation="Vertical" 
   Margin="25,0,0,0">
                            <Label Text="Upload Image:" 
     TextColor="#676767"  TextTransform="None"/>
                            <StackLayout Orientation="Horizontal">

                                <Frame CornerRadius="30"  Padding="0" 
        BorderColor="#0E305D" x:Name="ChooseFileImage_name">
                                    <Button 
                            VerticalOptions="Center"
                            Text="Choose File"
                            BackgroundColor="Transparent"
                            FontSize="Small"
                            Padding="10,5,10,5"
                            Clicked="UploadImage_Clicked">
                                    </Button>
                                </Frame>
                                <Image x:Name="ImgFile" 
     Aspect="AspectFit" HorizontalOptions="FillAndExpand" 
       BackgroundColor="White" HeightRequest="50">
                                    <Image.Source>
                                        <FontImageSource 
          Glyph="&#xf03e;"
                                             Color="#0E305D"
                                             Size="50"
                                             FontFamily="{StaticResource 
             FontAwesomeSolid}">
                                        </FontImageSource>
                                    </Image.Source>
                                </Image>
                                <Label x:Name="SelFileName" 
          HorizontalOptions="CenterAndExpand" FontSize="7"></Label>
                                <Image IsVisible="False" 
           x:Name="ImgClear" Margin="0,0,10,0">
                                    <Image.Source>
                                        <FontImageSource 
      Glyph="&#xf00d;" Color="Red" FontFamily="{StaticResource 
           FontAwesomeSolid}"></FontImageSource>
                                    </Image.Source>
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer 
           Tapped="DelImageicon_Tapped"></TapGestureRecognizer>
                                    </Image.GestureRecognizers>
                                </Image>
                            </StackLayout>
                        </StackLayout>
                    </StackLayout>
                    
                    
                    
        **//Page.xaml.cs** 


    public string GlypCode;
    string fileName = "";
    string filePath = "";
    long FileSize;
    Stream ImageStream;
         
    //upload image start
    private async void UploadImage_Clicked(object sender, EventArgs e)
    {
        if (Device.RuntimePlatform == Device.iOS)
        {
            allowedUtis = new string[] {
             UTType.PNG,
             UTType.PDF,
             UTType.JPEG,
             UTType.Image,
             "com.microsoft.word.doc",
             "org.openxmlformats.wordprocessingml.document",
             "org.openxmlformats.spreadsheetml.sheet",
             "com.microsoft.excel.xls"
             };
        }

        try
        {
            var customFileType = new FilePickerFileType(new 
             Dictionary<DevicePlatform, IEnumerable<string>>
                             {
                                 { DevicePlatform.iOS, allowedUtis },
                                 { DevicePlatform.Android, new[] { 
           "image/png", "image/jpeg" } },
                             });

            var result = await FilePicker.PickAsync(new PickOptions
            {
                PickerTitle = "Select",
                FileTypes = customFileType
            });

            string Contenttype = result.ContentType;
           

            SelFileName.Text = result.FileName;
            filePath = result.FullPath;
            fileName = result.FileName;
            FileSize = new FileInfo(result.FullPath).Length;
            FileStream fs = new FileStream(result.FullPath, 
         FileMode.Open, FileAccess.Read);
            StreamReader r = new StreamReader(fs);
            ImageStream = r.BaseStream;
            ImgClear.IsVisible = true;
            ChooseFileImage_name.IsVisible = false;

        }
        catch (Exception ex)
        {

        }
    }

    //upload image end






            private void DelImageicon_Tapped(object sender, EventArgs e)
            {
                GlypCode = "\uf03e";
                ImgFile.Source = new FontImageSource()
                {
                    Size = 100,
                    Color = Color.FromHex("#0E305D"),
                    Glyph = GlypCode,
                    FontFamily = 
      Application.Current.Resources["FontAwesomeSolid"] as 
         OnPlatform<string>
                };
                ImgFile.Aspect = Aspect.AspectFit;
                ImgClear.IsVisible = false;
                ChooseFileImage_name.IsVisible = true;
                SelFileName.Text = "";
                ImageStream = null;
            }       
Indian
  • 31
  • 3