有没有办法将字节转换为IFormFile c# .net 4.5

Is there a way to convert byte into IFormFile c# .net 4.5

提问人:Nahid 提问时间:7/26/2023 最后编辑:Nahid 更新时间:7/29/2023 访问量:60

问:

我有一个在 .NET 4.5 中实现的项目,由于某种原因,我无法更改它。我想将照片发布到使用 .NET Core 实现的 Web API。API 终结点使用 HTTP POST,其输入类型为泛型 ICollection,其类型为 IFormFile。但是,我甚至无法发送一张图片,因为我只能向 API 发送字节类型。我该如何解决这个问题?这是我的代码:

 using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(ServiceInfo.VIPCParams["DMSUri"].Value);
                client.DefaultRequestHeaders.Accept.Clear();
               // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", responseModelLogin.Token);

                // string json = JsonConvert.SerializeObject(parameters);
              // HttpContent content = new ByteArrayContent(uploadRequest.File);

               HttpContent content = new ByteArrayContent(uploadRequest.File);

                //HttpContent content = new StreamContent(stream);

                //content.Headers.ContentType = new MediaTypeHeaderValue("application/json");



                //using (var stream = new MemoryStream(uploadRequest.File))
                //{
                //    await documentRepository.UploadFile(stream);
                //}


               // content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                var multipartContent = new MultipartFormDataContent();
                multipartContent.Add(content);

               // multipartContent.Add(new StreamContent(content));

                HttpResponseMessage res = client.PostAsync(url, multipartContent).Result;
                string data = res.Content.ReadAsStringAsync().Result;
                mSUploadResponse = JsonConvert.DeserializeObject<DMSUploadResponse>(data);
            }
C# http-post net-4.5 iform文件

评论

0赞 Charlieface 7/26/2023
请不要发布代码或数据的图像,请仅以文本形式粘贴
0赞 Charlieface 7/26/2023
看起来您只需要对每个内部内容对象进行多次调用。也不要使用,因为你冒着死锁的风险,而是这样做multipartContent.Add.Resultawait
0赞 Nahid 7/29/2023
对不起,我在这里编辑了我的帖子并复制了我的代码。
0赞 Nahid 7/29/2023
我很困惑,因为我尝试使用 multipartContent.Add 将照片添加到我的帖子请求中,但它没有用。当我尝试使用 POST 方法发送请求时,服务器返回一个错误,说没有照片可上传
0赞 AbeMonk 7/29/2023
由于我看不到您的 API 代码,因此很难确定到底发生了什么。但是,根据我在 .NET API 中处理多部分数据的经验,我了解到,对作为 API 控制器实现一部分的对象执行操作效果很好。这将生成一个对象,其中包含一个对象,该对象包含表单数据中找到的所有文件。ReadFormAsync()RequestIFormCollectionIFormFileCollection

答: 暂无答案