IT박스

C # HttpClient 4.5 멀티 파트 / 양식 데이터 업로드

itboxs 2020. 7. 12. 10:22
반응형

C # HttpClient 4.5 멀티 파트 / 양식 데이터 업로드


누구나 HttpClient.Net 4.5에서 multipart/form-data업로드 와 함께 사용하는 방법을 알고 있습니까?

인터넷에서 예를 찾을 수 없습니다.


내 결과는 다음과 같습니다

public static async Task<string> Upload(byte[] image)
{
     using (var client = new HttpClient())
     {
         using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
         {
             content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");

              using (
                 var message =
                     await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
              {
                  var input = await message.Content.ReadAsStringAsync();

                  return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
              }
          }
     }
}

다음과 같이 다소 작동합니다 (image / jpg 파일을 사용하는 예).

async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData)
{
    var requestContent = new MultipartFormDataContent(); 
    //    here you can specify boundary if you need---^
    var imageContent = new ByteArrayContent(ImageData);
    imageContent.Headers.ContentType = 
        MediaTypeHeaderValue.Parse("image/jpeg");

    requestContent.Add(imageContent, "image", "image.jpg");

    return await client.PostAsync(url, requestContent);
}

( requestContent.Add()원하는대로 할 수 있습니다 . HttpContent 하위 항목 을 살펴보고 사용 가능한 유형을 확인하십시오.)

완료 HttpResponseMessage.Content되면와 함께 사용할 수있는 응답 콘텐츠를 찾을 수 있습니다 HttpContent.ReadAs*Async.


다음은 MultipartFormDataContent를 사용하여 HTTPClient로 문자열 및 파일 스트림을 게시하는 방법의 예입니다. 각 HTTPContent에 대해 Content-Disposition 및 Content-Type을 지정해야합니다.

여기 내 예가 있습니다. 그것이 도움이되기를 바랍니다.

private static void Upload()
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");

        using (var content = new MultipartFormDataContent())
        {
            var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4";

            string assetName = Path.GetFileName(path);

            var request = new HTTPBrightCoveRequest()
                {
                    Method = "create_video",
                    Parameters = new Params()
                        {
                            CreateMultipleRenditions = "true",
                            EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
                            Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
                            Video = new Video()
                                {
                                    Name = assetName,
                                    ReferenceId = Guid.NewGuid().ToString(),
                                    ShortDescription = assetName
                                }
                        }
                };

            //Content-Disposition: form-data; name="json"
            var stringContent = new StringContent(JsonConvert.SerializeObject(request));
            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
            content.Add(stringContent, "json");

            FileStream fs = File.OpenRead(path);

            var streamContent = new StreamContent(fs);
            streamContent.Headers.Add("Content-Type", "application/octet-stream");
            //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
            streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
            content.Add(streamContent, "file", Path.GetFileName(path));

            //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);

            var input = message.Result.Content.ReadAsStringAsync();
            Console.WriteLine(input.Result);
            Console.Read();
        }
    }
}

다음 HttpClient은를 업로드 하는 데 사용하는 방법에 대한 또 다른 예입니다 multipart/form-data.

파일을 REST API에 업로드하고 파일 자체 (예 : JPG) 및 추가 API 매개 변수를 포함합니다. 파일은를 통해 로컬 디스크에서 직접 업로드됩니다 FileStream.

추가 API 특정 로직을 포함한 전체 예제는 여기참조 하십시오 .

public static async Task UploadFileAsync(string token, string path, string channels)
{
    // we need to send a request with multipart/form-data
    var multiForm = new MultipartFormDataContent();

    // add API method parameters
    multiForm.Add(new StringContent(token), "token");
    multiForm.Add(new StringContent(channels), "channels");

    // add file and directly upload it
    FileStream fs = File.OpenRead(path);
    multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

    // send request to API
    var url = "https://slack.com/api/files.upload";
    var response = await client.PostAsync(url, multiForm);
}

나를 위해 일한 완전한 샘플이 있습니다. boundary요청 값은 .NET에 의해 자동으로 추가됩니다.

var url = "http://localhost/api/v1/yourendpointhere";
var filePath = @"C:\path\to\image.jpg";

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);

var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

form.Add(imageContent, "image", Path.GetFileName(filePath));
var response = httpClient.PostAsync(url, form).Result;

이 기능을 사용해보십시오.

private static async Task<object> Upload(string actionUrl)
{
    Image newImage = Image.FromFile(@"Absolute Path of image");
        ImageConverter _imageConverter = new ImageConverter();
        byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));

    var formContent = new MultipartFormDataContent
    {
    //send form text values here
         {new StringContent("value1"),"key1"},
         {new StringContent("value2"),"key2" },
    // send Image Here
         {new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}
    };

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
    string stringContent = await response.Content.ReadAsStringAsync();

    return response;
}

        X509Certificate clientKey1 = null;
        clientKey1 = new X509Certificate(AppSetting["certificatePath"],  
        AppSetting["pswd"]);
        string url = "Https://EndPointAddress";
        FileStream fs = File.OpenRead(FilePath);
        var streamContent = new StreamContent(fs);

        var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);            
        FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType");
        var handler = new WebRequestHandler();       


            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.ClientCertificates.Add(clientKey1);
            handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            };            


        using (var client = new HttpClient(handler))
        {
            // post it
            HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Result;
            if (!httpResponseMessage.IsSuccessStatusCode)
            {

                string ss = httpResponseMessage.StatusCode.ToString();
            }
        }   

DELETE http 동사를 통해 노출 된 API에 파일을 게시하는 방법을 보여주는 코드 스 니펫을 추가하고 있습니다. 이것은 DELETE http 동사로 파일을 업로드하는 일반적인 경우는 아니지만 허용됩니다. 전화 승인을 위해 Windows NTLM 인증을 가정했습니다.

The problem that one might face is that all the overloads of HttpClient.DeleteAsync method have no parameters for HttpContent the way we get it in PostAsync method

var requestUri = new Uri("http://UrlOfTheApi");
using (var streamToPost = new MemoryStream("C:\temp.txt"))
using (var fileStreamContent = new StreamContent(streamToPost))
using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
using (var httpClient = new HttpClient(httpClientHandler, true))
using(var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
using (var formDataContent = new MultipartFormDataContent())
{
       formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
       requestMessage.Content = formDataContent;
       var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
       if (response.IsSuccessStatusCode)
       {
             //file upload was successfull
       }
       else
       {
             var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
             throw new Exception("Error on the server : " + erroResult);
        }
}

You need below namespaces at the top of your C# file:

using System;
using System.Net;
using System.IO;
using System.Net.Http;

P.S. Sorry about so many using blocks(IDisposable pattern) in my code. Unfortunately, the syntax of using construct of C# doesn't support initializing multiple variables in single statement.


public async Task<object> PassImageWithText(IFormFile files)
{
  byte[] data;
  string result = "";
  ByteArrayContent bytes;

  MultipartFormDataContent multiForm = 
    new MultipartFormDataContent();
    try
    {
        using (var client = new HttpClient())
        {
            using (var br = new BinaryReader(files.OpenReadStream()))
                data = br.ReadBytes((int)files.OpenReadStream().Length);

            bytes = new ByteArrayContent(data);
            multiForm.Add(bytes, "files", files.FileName);
            multiForm.Add(new StringContent("value1"), "key1");
            multiForm.Add(new StringContent("value2"), "key2");

            var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);

        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }
    return result;
}

참고URL : https://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload

반응형