Upload c# files to API

Asked

Viewed 123 times

1

Hello! I was sending files doing POST for Azure Devops (documentation) via Javascript (just to test some features):

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/octet-stream; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');

request.send(file);

For security reasons I was migrating this to server-side methods, which I am using c#. I have reached this point:

//criando o request
WebRequest request = WebRequest.Create(url);
//headers
request.ContentType = "application/octet-stream; charset=UTF-8";
request.Headers.Add("Authorization", "Basic " + authorizationBasic);
request.Headers.Add("20", "application/json"); //20 = accept
request.Method = "POST";
request.ContentLength = 0;
//body
Stream dataStream = request.GetRequestStream();
dataStream = file.InputStream;
dataStream.Close();
//fazendo o request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// le o conteudo da resposta
using (Stream dataStreamResp = response.GetResponseStream())
{
    StreamReader reader = new StreamReader(dataStreamResp);
    string responseFromServer = reader.ReadToEnd();
}

I’m already consuming the ok API. I receive in return status 200 and the url of the file I uploaded as expected, but when opening the url of the answer it is all blank, that is, it is not sending the file, only its name.

I know that according to the documentation, I need to put in body one string with the Stream para upload, but I don’t know how to do it and I didn’t have much success also searching through the internet...

Thank you!

  • generally in your Datastream would use . write() to write the content to be uploaded

2 answers

1

Why don’t you change the WebRequest for WebClient, using it in this way:

using (WebClient WC = new WebClient())
{
    WC.UploadFileCompleted += UploadCompleted;
    WC.UploadProgressChanged += UploadProgress;
    WC.Headers.Add("name", "value.."); // headers..
    WC.Headers.Add("name", "value.."); // headers..

    WC.UploadFile("API", @"diretório do arquivo ao ser enviando.. (C:\Users\...\Desktop\....)");
}
private void UploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
    // ação após o envio ser completado..
}

private void UploadProgress(object sender, UploadProgressChangedEventArgs e)
{
    // ação durante o envio do arquivo..
}

Take a look at the documentation Webclient.Uploadfile Microsoft Method. Other than the use of UploadFileAsync and/or UploadFileTaskAsync to work asynchronously. I hope I helped you!

  • Thank you! I’ll test it here

  • In the "@" file directory when sending.. (C: Users... Desktop....)" how would I do? Because I am getting the file as a parameter, it is not stored in any directory

  • what parameter is this? is a Base64 or byte?

  • is an object HttpPostedFile I can turn into an object like Stream

  • I believe you will need to save this content Stream or Byte for the directory, example: .pdf file for "C: Users... Desktop.pdf file" ai on the line: @"file directory when sending.. (C: Users... Desktop....)" you put the directory... Let me see if I can find documentation for this type of action in C#

  • 1

    I found these two options here Httppostedfile.Inputstream Property and How do I save a stream to a file in C#? see if you can fix it, just don’t help him anymore 'cause I’m in a rush!

  • Thank you very much! I got it here, it was simpler than I thought kkkkkkkkkkkkkkkkkkkkkkkk I will put the answer

Show 2 more comments

0


I did it! The problem was obvious, I needed to define the size of the contentLength. I thought that if I set it to 0, it would mean that it would not have set size, but that’s not the case. Follow the code:

//criando o request
WebRequest request = WebRequest.Create(url);
//headers
request.ContentType = "application/octet-stream; charset=UTF-8";
request.Headers.Add("Authorization", "Basic " + authorizationBasic);
request.Headers.Add("20", "application/json"); //20 = accept
request.Method = "POST";

//mudando o body
request.ContentLength = file.InputStream.Length;
using(Stream streamRequest = request.GetRequestStream())
{
    file.InputStream.CopyTo(streamRequest);
}

//fazendo o request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

//Pega o response
using (Stream dataStream = response.GetResponseStream())
{
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.