【问题标题】:Buffer files to send a filestream to a backend缓冲文件以将文件流发送到后端
【发布时间】:2020-03-16 15:15:08
【问题描述】:

我正在为 UiPath RPA 工作流编写我的第一个自定义活动,在该工作流中我需要将文件流异步发送到后端。这是我想出的,但我只是觉得这不太行:

 class SendFiles : AsyncCodeActivity<string>
    {
        private readonly HttpClient client = new HttpClient();
        private readonly string url = "";

        [Category("Input")]
        [RequiredArgument]
        public InArgument<List<string>> Files { get; set; }

        [Category("Input")]
        [RequiredArgument]
        public string BearerToken { get; set; }

        [Category("Output")]
        public OutArgument JsonResult { get; set; }

        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {

            foreach (var filePath in Files.Get(context))
            {
                try
                {
                    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
                    {
                        HttpContent content = new StreamContent(fs);
                        client.PostAsync(url, content);
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine(e.Message);
                    throw;
                }
            }
            return null;
        }

        protected override string EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
        {
            throw new NotImplementedException();
        }
    }

发送整个批次后,我想等待后端处理所有这些文件的结果。我怎样才能做到这一点?

【问题讨论】:

    标签: asynchronous filestream rpa uipath


    【解决方案1】:
    // make outer content
    MultipartFormDataContent formdata = new MultipartFormDataContent();
    
    ...
    
    // in foreach add every filestream to outer content
    FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
    HttpContent content = new StreamContent(fs);
    string name = GetFileName(filePath);
    content.Headers.Add("Content-Type", GetFileType(name));
    formdata.Add(content, "files", name);
    
    ...
    
    // after foreach, send whole outer content in one go
    var resultPost = client.PostAsync(url, formdata).Result;
    response = resultPost.Content.ReadAsStringAsync().Result;
    succesfullRequest = resultPost.IsSuccessStatusCode;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-14
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2021-02-06
      • 2016-06-16
      相关资源
      最近更新 更多