• Xamarin Upload Files by WebAPI (Asp.Net Framework)


    WebApi Code

    public IHttpActionResult UploadFiles()
    {
      try
      {
          var request = HttpContext.Current.Request;
    
          if (request.Files.Count <= 0)
          {
              return StatusCode(HttpStatusCode.NoContent);
          }
          //Define files storage location
          string basePath = AppDomain.CurrentDomain.BaseDirectory + "Uploads\";
          if (!Directory.Exists(basePath))
          {
              Directory.CreateDirectory(basePath);
          }
          for (int i = 0; i < request.Files.Count; i++)
          {
              try
              {
                  var file = request.Files[i];
                  file.SaveAs(basePath + file.FileName);
              }
              catch (Exception ex)
              {
    
              }
          }
          return Ok();
    
      }
      catch (Exception ex)
      {
          return BadRequest();
      }
    }
    

    Xamarin Code

    private async void Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (SelectedFiles == null)
            {
                return;
            }
            //MultipartFormDataContent  : support select multiple files
            MultipartFormDataContent contents = new MultipartFormDataContent();
    
            //foreach the selected files and add it to contents
            foreach (var item in SelectedFiles)
            {
                //File Content(Stream) , name , FileName 
                contents.Add(new StreamContent(await item.OpenReadAsync()), "file", DateTime.Now.ToString("yyyyMMddHHmmss") + item.FileName);
            }
            //Post,Pass contents to WebApi
            var rs = await new HttpClient().PostAsync("UploadFiles", contents);
    
            //Verify reulst after WebApi processing
            if (rs .IsSuccessStatusCode)
            {
                await DisplayAlert("Tips","Success!","OK");
            }else
                await DisplayAlert("Tips","Error!","OK");
        }
        catch (Exception ex)
        {
    
        }
    }
    

    Xamarin Select File Code

    public IEnumerable<FileResult> SelectedFiles { get; set; }
    public async void SelectFiles()
    {
      //Select Multiple Files ,The File Type is Image
      SelectedFiles = await FilePicker.PickMultipleAsync(PickOptions.Images);
    }
    
  • 相关阅读:
    python 返回函数的使用
    你的服务器还在裸奔吗?
    云计算产品vSwitch原理
    网卡创建Bond
    UI自动化框架介绍
    常用底层linux命令
    Linux Bridge基本概念
    磁盘格式化及设置自动挂载
    Linux vi文本编辑器常用命令
    MySQL5.7安装方式
  • 原文地址:https://www.cnblogs.com/LingLis/p/14701780.html
Copyright © 2020-2023  润新知