C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 904
逝去的感伤
逝去的感伤 2020-11-22 05:39

Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?

I couldn\'t find any examples on the internet.

相关标签:
10条回答
  • 2020-11-22 05:48
    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:49

    It works more or less like this (example using an image/jpg file):

    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);
    }
    

    (You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)

    When completed, you'll find the response content inside HttpResponseMessage.Content that you can consume with HttpContent.ReadAs*Async.

    0 讨论(0)
  • 2020-11-22 05:56

    Try this its working for me.

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 05:57

    Example with preloader Dotnet 3.0 Core

    ProgressMessageHandler processMessageHander = new ProgressMessageHandler();
    
    processMessageHander.HttpSendProgress += (s, e) =>
    {
        if (e.ProgressPercentage > 0)
        {
            ProgressPercentage = e.ProgressPercentage;
            TotalBytes = e.TotalBytes;
            progressAction?.Invoke(progressFile);
        }
    };
    
    using (var client = HttpClientFactory.Create(processMessageHander))
    {
        var uri = new Uri(transfer.BackEndUrl);
        client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", AccessToken);
    
        using (MultipartFormDataContent multiForm = new MultipartFormDataContent())
        {
            multiForm.Add(new StringContent(FileId), "FileId");
            multiForm.Add(new StringContent(FileName), "FileName");
            string hash = "";
    
            using (MD5 md5Hash = MD5.Create())
            {
                var sb = new StringBuilder();
                foreach (var data in md5Hash.ComputeHash(File.ReadAllBytes(FullName)))
                {
                    sb.Append(data.ToString("x2"));
                }
                hash = result.ToString();
            }
            multiForm.Add(new StringContent(hash), "Hash");
    
            using (FileStream fs = File.OpenRead(FullName))
            {
                multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(FullName));
                var response = await client.PostAsync(uri, multiForm);
                progressFile.Message = response.ToString();
    
                if (response.IsSuccessStatusCode) {
                    progressAction?.Invoke(progressFile);
                } else {
                    progressErrorAction?.Invoke(progressFile);
                }
                response.EnsureSuccessStatusCode();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:57
    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;
    }
    
    0 讨论(0)
  • 2020-11-22 06:03

    Here's a complete sample that worked for me. The boundary value in the request is added automatically by .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;
    
    0 讨论(0)
提交回复
热议问题