1

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


        }

}

5
  • Look into HttpWebRequest. Commented Sep 8, 2015 at 6:35
  • Check restsharp.org Commented Sep 8, 2015 at 6:40
  • me be help stackoverflow.com/questions/10347396/… Commented Sep 8, 2015 at 6:43
  • 1
    I'm voting to close this question as off-topic because this question lacks minimal effort to solve the problem. Commented Sep 8, 2015 at 6:49
  • You can have a look at HttpClient Commented Sep 8, 2015 at 6:52

1 Answer 1

1

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.