3

enter image description here

public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
    var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
    WebClient webClient = new WebClient();
    byte[] responseBinary = webClient.UploadFile(apiUrl, file.FileName);
    string response = Encoding.UTF8.GetString(responseBinary);
    /* Giving error here. How to proceed?
}

I want to upload a single file to this url and the response is shown in the figure above. How to proceed further with the same in C#? Please help

2
  • Try using fiddler to take a peak at the communications between your client and the server. Might give a hint as to what is breaking (for instance, problems in the way the data is being sent, or http error codes will be easier to interpret in fiddler than trying to debug this). Please post the results. Commented May 26, 2015 at 13:58
  • Easy way to upload a file using api call is Convert your File into base64 string and send string on server then on server side Convert base64 string to file and store in directory. Commented Dec 5, 2015 at 9:28

1 Answer 1

0

Try your code like below.

public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
    var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
    
    using (HttpClient client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            byte[] fileBytes = new byte[file.InputStream.Length + 1];                         
            file.InputStream.Read(fileBytes, 0, fileBytes.Length);
            var fileContent = new ByteArrayContent(fileBytes);
            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
            content.Add(fileContent);
            var result = client.PostAsync(apiURL, content).Result;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new 
                {
                    code = result.StatusCode,
                    message = "Successful",
                    data = new 
                    {
                        success = true,
                        filename = file.FileName
                    }
                };
            }
            else
            {
                return new 
                {
                    code = result.StatusCode,
                    message = "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.