简体   繁体   中英

Send Data to Web API using C#

I was using the following code to send fromData contains 2 values (File and String) to a WebAPI using javascript.

var formData = new FormData();  
formData.append('name', 'previewImg');
formData.append('upload', $('input[type=file]')[0].files[0]); 
$.ajax({
url: 'WebAPI url',
data: formData,    
contentType: false,
processData: false,
// ... Other options like success and etc
})

I want to do the same thing using C# Windows Application, I need to write a Method accepts 2 paramters (FilePath and String) then send the file and the string to WebAPI.

I tried the following code but it returns an error from the service( I am trying to contact with koemei upload service) , although it works fine when I call it from Js :

void SendData(string filepath,string name){
        var url = "URL";

        HttpContent fileContent = new  ByteArrayContent(System.IO.File.ReadAllBytes(filepath));

        using (var client = new HttpClient())
        {
            using (var formData = new MultipartFormDataContent())
            {
                formData.Add(fileContent, "upload");

                formData.Add(new StringContent(name), "name");


                //call service
                var response = client.PostAsync(url, formData).Result;

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception();
                }
                else
                {

                    if (response.Content.GetType() != typeof(System.Net.Http.StreamContent))
                        throw new Exception();

                    var stream = response.Content.ReadAsStreamAsync();
                    var content = stream.Result;

                    var path = @"name.txt";
                    using (var fileStream = System.IO.File.Create(path))
                    {
                        content.CopyTo(fileStream);
                    }
                }
            }


        }

}

Here is a sample

private List<ByteArrayContent> GetFileByteArrayContent(HashSet<string> files)
{
    List<ByteArrayContent> list = new List<ByteArrayContent>();
    foreach (var file in files)
    {
        var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = Path.GetFileName(file)
        };
        list.Add(fileContent);
    }
    return list;
}
private List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
{
    List<ByteArrayContent> list = new List<ByteArrayContent>();
    foreach (var key in collection.AllKeys)
    {
        var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
        dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            Name = key
        };
        list.Add(dataContent);
    }
    return list;
}

And here is how to post the data and files

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));//set how to get data
    using (var content = new MultipartFormDataContent())//post by content type multipart/form-data
    {
        NameValueCollection dataCollection;//the datas you want to post
        HashSet<string> filePaths;//the files you want to post
        var formDatas = this.GetFormDataByteArrayContent(dataCollection);//get collection
        var files = this.GetFileByteArrayContent(filePaths);//get collection
        Action<List<ByteArrayContent>> act = (dataContents) =>
        {//declare an action
            foreach (var byteArrayContent in dataContents)
            {
                content.Add(byteArrayContent);
            }
        };
        act(formDatas);//process act
        act(files);//process act
        try
        {
            var result = client.PostAsync(this.txtUrl.Text, content).Result;//post your request
        }
        catch (Exception ex)
        {
            //error
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM